skip to Main Content

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


  1. 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

    Login or Signup to reply.
  2. 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!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search