Andy Andy - 4 years ago 150
PHP Question

PHP - Delete from multi-dimensional array by value

I have a multi-dimensional PHP array and want to remove any elements (on a row basis) which do not match a value.

For example:

$user_types = [
0 => ['ut_id' => 32, 'type' => 'admin'],
1 => ['ut_id' => 31, 'type' => 'user'],
2 => ['ut_id' => 801, 'type' => 'editor']
];


Let's say I only want the element where
'type' == 'admin'
. I want the output to be:

$user_types = [
0 => ['ut_id' => 32, 'type' => 'admin']
]


I also need to ensure that the array is keyed sequentially. So if I only want
type == 'editor'
the array key should still be 0 (not 2), e.g.

$user_types = [
0 => ['ut_id' => 801, 'type' => 'editor']
]


I've had a look at PHP array delete by value (not key) but this does not deal with multi-dimensional arrays.

I've also seen some solutions which use a
foreach
loop, but that seems quite inefficient.

Please can someone point me in the direction of what to look at? I can't find any examples that deal with this when it comes to multidimensional arrays. I have seen Delete element from multidimensional-array based on value but this seems inefficient and was written about 6 years ago.

Answer Source

You can use php's array_filter() function here:

<?php
$user_types = [
    0 => ['ut_id' => 32, 'type' => 'admin'],
    1 => ['ut_id' => 31, 'type' => 'user'],
    2 => ['ut_id' => 801, 'type' => 'editor']
];

$type = 'admin';
print_r(
    array_values(
        array_filter($user_types, function($entry) use ($type){
            return $entry['type'] === $type;
        })
    )
);

$type = 'editor';
print_r(
    array_values(
        array_filter($user_types, function($entry) use ($type){
            return $entry['type'] === $type;
        })
    )
);

The output of above code is:

Array
(
    [0] => Array
        (
            [ut_id] => 32
            [type] => admin
        )

)
Array
(
    [0] => Array
        (
            [ut_id] => 801
            [type] => editor
        )

)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download