'Print out select options dropdown inside echo

How do I print out select option inside echo ? I have now this:

echo '<select name="api_series">
       <?php foreach($series["data"] as $data) { echo <option>$data["id"]</option> } ?>
      </select>';

But this doesnt work. How do I make this work I am so confused.

php


Solution 1:[1]

You can't open a new PHP code block (with <?php) or put a foreach loop or an echo inside an existing PHP block and echo statement / string. And even if that was possible somehow, it would make no logical sense. You just need to do the loop, concatenate the string as you go along and then echo it. Or you could echo each chunk of content directly as you loop.

For example:

$html = '<select name="api_series">';

foreach ($series["data"] as $data) { 
  $html .= '<option>'.$data["id"].'</option>';
} 
$html .= '</select>';

echo $html;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1