0

I would like to be able to store the following select element, complete with the php foreach loop that constructs it, inside a variable, that can then be included in a dynamically created form.(the first two lines are just showing what $statement and $lengths are.) The solution i tried is down below, but it won't let me put a foreach loop within a variable.

   //$statement = 'in %s days %s will have the most followers'
   //$lengths = array([0]=>'3 days',[1]=>'4 days',[2]=>'6 days')

   <select name="timeframe">  
     <?php foreach($lengths as $length)
     {
       echo "<option value = " . $length . "/>" . $length . "</option>";
     }?> 
    </select> 

Here is my first attemt solution(failed):

<?php
 $select_a = '<select name="timeframe">' .  
   foreach($lengths as $length)
 {
   echo "<option value = " . $length . "/>" . $length . "</option>";
 } . '</select>';

 $select_b = '<select name="celebrity">' . 
   foreach($names as $name)
 {
   echo "<option value = " . $name . "/>" . $name . "</option>";
 } . '</select>';?>

The reason I'm doing this is because the arrays($lengths and $names) will each be stored in serialized form in a database(then unserialized to be able to loop through here), and in a third field will be a statement with %s placeholders. The final result would be that I can just echo out the below within a html form element.

1
  • here is how I would like to echo out the final result:<?php echo sprintf($statement, $select_a, $select_b);?> Commented Oct 28, 2013 at 3:45

1 Answer 1

1

Instead of using echo's and new variables like that, you can just use $select_a .= X. The .= operator adds values or strings to an variable, instead of replacing the old ones.

So in your case you could write:

$select_a = '<select name="timeframe">';  
foreach($lengths as $length)
{
$select_a .= "<option value = " . $length . "/>" . $length . "</option>";
} 
$select_a .= '</select>';

$select_b = '<select name="celebrity">'; 
foreach($names as $name)
{
$select_b .= "<option value = " . $name . "/>" . $name . "</option>";
}
$select_b .= '</select>';
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. Please mark the answer as correct if it solved your issue and was correct for your question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.