Jerrald Jerrald - 3 months ago 13
PHP Question

PHP List all instead of 1

I have this code which should show all the

$scheme
values in a
<ul>
. As you can see below, I have 2
$scheme
variables, but only 1 shows up in the
<ul>
.

$scheme = colorscheme('Test', 'hello');
$scheme = colorscheme('Black', 'hello');

function colorscheme( $color, $url ) {
return array( $color, $url );
}

echo '<ul>';
foreach ($scheme as $value) {
echo '<li>' . $value . '</li>';
}
echo '</ul>';


How can I make it so every
$scheme
shows up instead of only 1?

Answer

As you can see below, I have 2 $scheme variables, but only 1 shows up in the <ul>.

That's because $scheme variable gets overwritten with each function call. See here,

$scheme = colorscheme('Test', 'hello');  // Here, $scheme = array('Test', 'hello');
$scheme = colorscheme('Black', 'hello'); // Here, $scheme = array('Black', 'hello');

How can I make it so every $scheme shows up instead of only 1?

Make $scheme as an array, and append the returned array, from colorscheme() function, to this array, like this:

$scheme = array();
$scheme[] = colorscheme('Test', 'hello');
$scheme[] = colorscheme('Black', 'hello');

And then loop through this $scheme array using foreach loop to display all color schemes.

echo '<ul>';
foreach ($scheme as $colorscheme) {
    foreach($colorscheme as $value){
        echo '<li>' . $value . '</li>';
    }
}
echo '</ul>';