PHP List all instead of 1
Get the solution ↓↓↓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, fromcolorscheme()
function, to this array, like this:
$scheme = array();
$scheme[] = colorscheme('Test', 'hello');
$scheme[] = colorscheme('Black', 'hello');
And then loop through this$scheme
array usingforeach
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>';
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: php_network_getaddresses: getaddrinfo failed: temporary failure in name resolution
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.