I’m working with foreach loops for the first time and I don’t understand exactly how to pull a value obtained inside the foreach loop out of the loop. Here I have a small example, my code is bigger but this will work:
<?php
$colors = array("red", "green", "blue", "yellow");
$pimpoyo= [];
foreach ($colors as $value) {
$pimpoyo= "$value <br>";
break;
}
echo $pimpoyo;
?>
Result: red
If I remove the break then I get the last value like this. I don’t know how to get allof the values of $pimpoyo.
Any suggestions?
2
Answers
I think you need to append strings.
For more details about .= in php docs
Although your question is not completely clear (not to me, at least), it looks like you are now converting an array into an array.
$colors is an array with some colors.
You foreach these values and store them again in an array (seems to be what you want, looking at the code).
If you would like that to work, you have to do it like this:
Your code could be interpretated otherwisely as if you want to convert the array into a string and echo each value with a break. In that case the code is like this:
Let me know if this is working!