1

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.

4
  • I would look into multi-dimensional array searches and go from there. I will note that numerically indexed arrays always start at 0. You can't have a single element with a key of 2. Commented Feb 6, 2017 at 10:05
  • 1
    php.net/manual/en/function.array-filter.php in combination with array_values. Commented Feb 6, 2017 at 10:05
  • 1
    @StuartWagner Yes you can, there is no such restriction on the array key in php. Commented Feb 6, 2017 at 10:06
  • 1
    @jeroen You're absolutely right. My mistake. Commented Feb 6, 2017 at 10:16

1 Answer 1

3

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
        )

)
Sign up to request clarification or add additional context in comments.

1 Comment

Works perfectly and very efficient, Thank you. Will accept as the answer in a few mins when SO allows me to :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.