In PHP, what’s the best practice for dealing with a loop in a variable? Let me explain.
I have a file called index.php which contains the following:
<?php
$SELECT_INDUSTRY = array("Industry1", "Industry2", "Industry3");
require_once('form.inc');
?>
<html>
<head></head>
<body>
<?php echo $FORM_FIELD_INDUSTRY ?>
</body>
</html>
I then have a second file called form.inc:
<?php
$FORM_FIELD_INDUSTRY = '<select><option value=>Select an Industry</option>'.$INDUSTRY.'</select>';
?>
Here’s what is needed. I’d like to pass over the array values that are entered, into a foreach to process the array and spit out the <option></option> code. Here’s an example:
foreach ($SELECT_INDUSTRY as $INDUSTRY) {
echo '<option value="$INDUSTRY">$INDUSTRY</option>';
}
So this function would build my select options based on the array values. This works, but how would I be able to then pass the total values into a variable that I’ve defined in the form.inc file above? In the form.inc file, I have $INDUSTRY as the variable, which I suppose needs some sort of return from the other function. This may also need global variables to pass between functions if it comes to it. Is there a better way of handling this?
My end goal is to have the variable $FORM_FIELD_INDUSTRY which spits out the foreach function based on the array values.
SOLUTION
The solution is listed below, but for anyone coming across this, here is what I did:
index.php
<?php
$SELECT_INDUSTRY = array("Industry1", "Industry2", "Industry3");
$FORM_SELECT_SIZE = '';
require_once('form.inc');
?>
<html>
<head></head>
<body>
<?php get_options( $FORM_FIELD_INDUSTRY ) ?>
</body>
</html>
form.inc
<?php
function get_options( $arr = array() ) {
global $FORM_SELECT_SIZE;
echo '<select id="industry" class="'.$FORM_SELECT_SIZE.'"><option value=>Select an Industry</option>';
foreach( $arr as $option ) {
echo '<option>'.$option.'</option>';
}
echo '</select></div></div>';
}
$FORM_FIELD_INDUSTRY = $SELECT_INDUSTRY;
?>
Pretty simple solution for passing values between the function, and variables.
You could just use a function to build the options and return it like so:
And then in your HTML you could call it like this:
So if I were to take the code you gave us on top and combined it all it would look like this: