phparraysarray-push

How to push element after a certain value of an array


So we all know that array_push works like this:

<?php
$a=array("red","green");
array_push($a,"blue","yellow");
print_r($a);
?>

So the result would be:

Array ( [0] => red [1] => green [2] => blue [3] => yellow )

But now I need to know how can I append the blue and yellow after a certain value of the array.

So for example, if I determine that, push the blue and yellow after the red (which has the position of 0), this result would be shown:

Array ( [0] => red [1] => blue [2] => yellow [3] => green)

So how can I push element after a certain value of an array?


Solution

  • You can't do this with array_push. However, you can loop on the array, collect the values in a new array and array_merge the new colors when you find the color of your choice after which new colors need to be injected.

    <?php
    
    $a = array("red","green");
    
    $newColors = ["blue","yellow"];
    
    $result = [];
    
    foreach($a as $color){
      $result[] = $color;
      if($color == 'red'){
        $result = array_merge($result, $newColors);
      }
    }
    
    
    print_r($result);
    

    Online Demo