Search code examples
phpmybb

Foreach PHP loop with HTML code


I am trying to loop through an array and print HTML.

<?php
$categories = array('Hardware', 'Software', 'Game Items', 'Game Accounts');
?>

Some HTML goes here. I just wanted the array at the top of the page for easy edit.

<?php
foreach($categories as $category){

    echo "<option value=\"Hardware\"{$GLOBALS['filters_set']['trdfcat']['selected']['\" . $category . \"']}>\" . $category . \"</option>\""

}
?>

I am having a hard time trying to get the syntax right on this echo part. Some reason wont echo right which I think it is because of the parentheses.

The original HTML code is

<option value="Hardware"{$GLOBALS['filters_set']['trdfcat']['selected']['Hardware']}>Hardware</option>

It has to echo just like this.


Solution

  • It looks like you have some syntax errors with the quotation marks. Try concatenating the variables:

    echo "<option value='Hardware" . $GLOBALS['filters_set']['trdfcat']['selected'][$category] . "'>$category</option>";
    

    If you really want to interpolate:

    echo "<option value='Hardware{$GLOBALS['filters_set']['trdfcat']['selected'][$category]}'>$category</option>";
    

    You can also split things up if it makes it easier:

    echo "<option value='Hardware";
    echo $GLOBALS['filters_set']['trdfcat']['selected'][$category];
    echo "'>$category</option>";