James
James

Reputation: 318

PHP get modified array that matches a certain value

I have an array of arrays like below:

        Array
(
    [0] => Array
        (
            [id] => 1
            [uid] => 746
            [lid] => 748
        )

   [1] => Array
        (
            [id] => 6
            [uid] => 746
            [lid] => 744
        )

   [2] => Array
        (
            [id] => 11
            [uid] => 749
            [lid] => 743
        )


)

What I want is to get the modified array that has uid of say 746. So the result I would expect is:

Array
    (
        [0] => Array
            (
                [id] => 1
                [uid] => 746
                [lid] => 748
            )

       [1] => Array
            (
                [id] => 6
                [uid] => 746
                [lid] => 744
            )


    )

Is there any quick way to do it rather than loop through each element and save the matching array to the return array?

Upvotes: 1

Views: 55

Answers (1)

Jim
Jim

Reputation: 22656

There's no way to do it without inspecting each element. That being said you can use array_filter to do this (though it will loop behind the scenes):

$arr = array_filter($arr, function($item){
    return $item['uid'] == 746;
});

Prior to PHP 5.3.0 you will have to declare a function:

function filter746($item){
    return $item['uid'] == 746;
}
$arr = array_filter($arr, 'filter746');

Upvotes: 1

Related Questions