PHP List all instead of 1 ← (PHP)

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



Solution:

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>';

Answer



Solution:

By using the same variable name twice, you're just overwriting it on the second line. You need to use unique variable names for each scheme, or hold them all in an array (which would be preferable).

Also, your function serves no purpose whatsoever and is redundant.

In simple terms you could put all the schemes into a multi-dimensional array, which is an array comprised of sub-arrays. Then loop through the main array and retrieve the two elements of each sub-array so you can echo them.

$schemes = array(
    array('White', 'scheme 1'),
    array('Black', 'scheme 2'),
    array('Green', 'scheme 3')
);

echo '<ul>';
foreach ($schemes as $scheme) {
    $color = $scheme[0];
    $url = $scheme[1];
    echo "<li>$color = $url</li>";
}
echo '</ul>';

Source