Skip to content
Advertisement

Get item in array according to the value of a key within the item

Suppose I have an array like this:

$myArray = [
    [ 'id' => 1, 'name' => 'Some Name' ],
    [ 'id' => 2, 'name' => 'Some Other Name ] 
]

Now if want to get the second item without using the index ($myArray[1]), but instead by using the value of name which is Some Other Name, how do I do that?

I don’t want to loop through the entire array just for one value, so how can I write this in a way that I don’t explicitly loop through the array myself? I looked into array_search(), but couldn’t find examples where $myArray contains additional arrays as items.

Advertisement

Answer

you can use array_filter() function:

<?php

$myArray = [
    ['id' => 1, 'name' => 'Some Name'],
    [
        'id' => 2, 'name' => 'Some Other Name'
    ]
];


$filterData = array_filter($myArray, function ($data) {
    return $data['name'] == "Some Other Name";
});
var_dump($filterData);
die;
?>
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement