mardi 19 avril 2016

How to remove all items of array except specific one?

I have a variable which is containing these nested arrays:

echo $var;

/* Output:
Array(
       [0] => Array
         (
             [id] => 1
             [box] => 0
         )

       [2] => Array
         (
             [id] => 2
             [box] => 0
         )

       [3] => Array
         (
             [id] => 3
             [box] => 1
         )
) */

Now I want to remove all items of array above except $numb = 2;. I mean I want this output:

echo newvar;

/* Output:
Array(
       [2] => Array
         (
             [id] => 2
             [box] => 0
         )
) */

How can I do that?


Actually I can do a part of it by using if statement and array_shift() function:

foreach($var as $key => $val) {
    if($val["id"] != 2) {
        array_shift($var);
    }
}

But the output of code above isn't want I need.

Aucun commentaire:

Enregistrer un commentaire