0

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.

Community
  • 1
  • 1
Andy
  • 5,142
  • 11
  • 58
  • 131

1 Answers1

2

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
        )

)
arkascha
  • 41,620
  • 7
  • 58
  • 90
  • Works perfectly and very efficient, Thank you. Will accept as the answer in a few mins when SO allows me to :) – Andy Feb 06 '17 at 10:13