using array_search for multi dimensional array
function find_car_with_position($cars, $position) {
foreach($cars as $index => $car) {
if($car['Position'] == $position) return $index;
}
return FALSE;
}
You can try this
array_search(1, array_column($cars, 'position'));
In php 5.5.5 & later versions, you can try this
$array_subjected_to_search =array(
array(
'name' => 'flash',
'type' => 'hero'
),
array(
'name' => 'zoom',
'type' => 'villian'
),
array(
'name' => 'snart',
'type' => 'antihero'
)
);
$key = array_search('snart', array_column($array_subjected_to_search, 'name'));
var_dump($array_subjected_to_search[$key]);
Output:
array(2) { ["name"]=> string(5) "snart" ["type"]=> string(8) "antihero" }
working sample : http://sandbox.onlinephpfunctions.com/code/19385da11fe0614ef5f84f58b6dae80bd216fc01
Documentation about array_column can be found here
Hooray for one-liners!
$index = array_keys(array_filter($array, function($item){ return $item['property'] === 'whatever';}))[0];
Let's make it more clear:
array_filter(
$array,
function ($item) {
return $item['property'] === 'whatever';
}
);
returns an array that contains all the elements that fulfill the condition in the callback, while maintaining their original array keys. We basically need the key of the first element of that array.
To do this we wrap the result in an array_keys()
call and get it's first element.
This specific example makes the assumption that at least one matching element exists, so you might need an extra check just to be safe.