Reputation: 509
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.
Upvotes: 0
Views: 1155
Reputation: 11430
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>';
Upvotes: 1