Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

any suggestions? From already thank you very much

>Solution :

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!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading