Home > database >  how to extract a value that is inside a foreach loop out of the loop?
how to extract a value that is inside a foreach loop out of the loop?

Time:11-28

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 all the values of $pimpoyo.

any suggestions? From already thank you very much

CodePudding user response:

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:

<?php  
$colors = array("red", "green", "blue", "yellow"); 

$pimpoyo= [];
foreach ($colors as $value) {
  $pimpoyo [] = $value;
}
print_r ($pimpoyo);

?>

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:

<?php  
$colors = array("red", "green", "blue", "yellow"); 

$pimpoyo= '';
foreach ($colors as $value) {
  $pimpoyo .= $value . '<br>';
}
echo $pimpoyo;

?>

Let me know if this is working!

CodePudding user response:

I think you need to append strings.

<?php  
$colors = array("red", "green", "blue", "yellow"); 

$pimpoyo= "";
foreach ($colors as $value) {
  $pimpoyo .= "$value <br>";
}
echo $pimpoyo;

?> 

For more details about .= in php docs

  • Related