Insert value in array in a given position through a conditional

2

I have the following array:

array(143) {
 [0]=>
 string(0) ""
 [1]=>
 string(0) ""
 [2]=>
 string(5) "item1"
 [3]=>
 string(5) "item2"
 [4]=>
 string(5) "item3"
}

and my following logic to find a value in the array:

$abaixo = "item2";
foreach ($arrayName as $key => $value) {
        if (strpos($value, $abaixo)) {
          // aqui ele vai mostrar o "item2", 
          // ou seja, ele ta na posicao do "item2"
        }
}

I needed to know a way to give a array_push() after that position found, that is, I'm looking for in the array my $abaixo which is item2 there he found, I need to insert a value, under item2

Thank you

ANSWER

    foreach ($arrayName as $key => $value) {
        if (strpos($value, $abaixo)) {
            $posicao = $key + 1;
            array_splice($arrayName, $posicao, 0, $arrayInsert);
        }
    }
    
asked by anonymous 24.09.2015 / 15:17

1 answer

4

Let's assume your array is a collection like this:

$colecao = ['item1','item2','item4','item5'];

And you want to insert an item in key 2, after the missing key 1 (item2) called "item3", just do this:

array_splice($colecao, 2, 0, "item3");

And then you can continue your foreach .

See working here: link

    
24.09.2015 / 15:55