stack stack - 7 months ago 52
PHP Question

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;
(the value of id). 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.

Answer

You can use a slightly different loop.

foreach ($var as $item) {
    if ($item['id'] == 2) {
        $newvar = $item;
        break;
    }
}

You could also use array_filter

$newvar = array_filter($var, function($x) { return $x['id'] == 2; });

but it would most likely be less efficient as it would have to check every element of the array.