Reputation: 10228
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.
Upvotes: 0
Views: 8932
Reputation: 1656
array_reduce() would also do the job:
$array = [
['id' => 1, 'box' => 0],
['id' => 2, 'box' => 0],
['id' => 3, 'box' => 1]
];
$id = 2;
$result = array_reduce ($array, function ($carry, $item) use ($id) {
if ( $item['id'] === $id )
$carry[$item['id']] = $item;
return $carry;
}, []);
Upvotes: 1
Reputation: 41820
You can use a slightly different loop.
foreach ($var as $item) {
if ($item['id'] == 2) {
$newvar = $item;
break;
}
}
You could also use array_filter
$id = 2;
$newvar = array_filter($var, function($x) use ($id) { return $x['id'] == $id; });
but it would most likely be less efficient as it would have to check every element of the array.
Upvotes: 3
Reputation: 9676
You could just make a new array:
$oldArray = array(0 => 'a', 1 => 'b', 2 => 'c', 3=> 'd');
$index = 2;
$newArray = array($index => $oldArray[$index]);
// or even
$newArray = [$index => $oldArray[$index]];
If you don't need to preserve the index you can just do:
$newArray = [$oldArray[$index]];
Upvotes: 1
Reputation: 1832
I'm wondering how much context would help us with answering your question... Here is an answer to what you asked:
$newArray = array($var[2]);
Upvotes: 5