0

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
8
  • 1
    what do you mean by reshuffle? Commented Oct 25, 2016 at 18:41
  • You iterate over your array from beginning to end. Doing any kind of reshufling during this iteration seems useless to me and may lead to unforseen behaviour of a loop. Commented Oct 25, 2016 at 18:44
  • BTW, adding new array to array can be done with array_merge in one line of code. Commented Oct 25, 2016 at 18:45
  • @JeffPuckettII which array me added in foreach that should come first Commented Oct 25, 2016 at 18:50
  • Is there any structure in your sorting? Like alphabetical, etc. ? You could apply a custom sorting function with usort. Commented Oct 25, 2016 at 18:58

3 Answers 3

1

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;

Sign up to request clarification or add additional context in comments.

Comments

1

A cool solution would be like this:

$array = array('red', 'blue');
$others = array('white', 'yellow');

$temp = array_combine($array,$others);

$final = array();

foreach($temp as $key => $value) {
    array_push($final,$key,$value);
}

$array = $final;

Comments

0
$i = true;
$array = array('red', 'blue');
foreach($array as $key => & $value) {
    echo $value . '<br />';
    if ($i === true) {
          $a1= $array;
          $a2= array($value);
          $result=array_diff($a1,$a2);

          $others = array('white', 'yellow');
          $array =  array_merge($others,$result);
    }
    $i = false;
}

see output

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.