Web Developer Web Developer - 1 month ago 7
PHP Question

reshuffle array value in foreach loop

I am adding other value array inside foreach loop which working fine for me.

$i = true;
$array = array('red', 'blue');
foreach($array as $key => & $value) {
echo $value . '<br />';
if ($i === true) {
$others = array('white', 'yellow');
foreach($others as $key => & $other_value) {
$array[] = $other_value;
}
}
$i = false;
}


Output

red
blue
white
yellow


but i want to reshuffle array value inside foreach loop need output like below

red
white
yellow
blue

Answer

You won't be able to do it on $array without some serious array_slice()ing. So, just assign to another array $result and you will get the $other array inserted between the first and second elements of $array:

$i = true;
$array = array('red', 'blue');
foreach($array as $value) {
    $result[] = $value;  // here...
    if ($i === true) {
         $others = array('white', 'yellow');
         foreach($others as $other_value) {
             $result[] = $other_value;  // and here...
         }

    }
    $i = false;
}

If needed (for whatever reason) $array = $result;