Insert value into the array at a given position via a conditional

Asked

Viewed 1,917 times

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"
        }
}

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

thank you

REPLY

    foreach ($arrayName as $key => $value) {
        if (strpos($value, $abaixo)) {
            $posicao = $key + 1;
            array_splice($arrayName, $posicao, 0, $arrayInsert);
        }
    }
  • It’s no longer simple to use in_array(), if the value found in strpos be at zero position will give false.

  • 1

    dá uma olhada aqui: http://php.net/manual/en/function.array-unshift.php [add inicio] http://php.net/manual/en/function.array-push.php [add final]
http://php.net/manual/en/function.array-pop.php [remove final]
http://php.net/manual/en/function.array-shift.php [remove inicio] http://php.net/manual/en/function.array-splice.php [add parse] http://php.net/manual/en/function.array-slice.php [remove parse] http://php.net/pt_BR/function.array-merge.php [joint arrays]

  • 1

    @Furlan If your answer was the one you ended up using, rather than the end of the question, it’s best to create an answer and mark as accepted. It’s okay to do that :)

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 key 1 (item2) that was missing called "item3", just do this:

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

And then you can continue yours foreach.

See working here: http://ideone.com/12IPOk

Browser other questions tagged

You are not signed in. Login or sign up in order to post.