35

using array_search in a 1 dimensional array is simple

$array = array("apple", "banana", "cherry");
$searchValue = "cherry";
$key = array_search($searchValue, $array);

echo $key;

but how about an multi dimensional array?

    #RaceRecord

    [CarID] [ColorID] [Position]
[0]    1        1         3
[1]    2        1         1
[2]    3        2         4
[3]    4        2         2
[4]    5        3         5

for example i want to get the index of the car whose position is 1. How do i do this?

2
  • 3
    An "associative array" and a "multidimensional array" are two different things. Your example is a multidimensional array that happens to have one axis being associative.
    – Amber
    Oct 8, 2011 at 4:40
  • oh i see sorry, im gonna edit the title Oct 8, 2011 at 4:46

6 Answers 6

66

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

4
  • what if I need to search where name = snart and type = antihero
    – Smith
    Nov 14, 2017 at 21:08
  • @Smith :Use Loupax's answer & combine your matches in the return statement with &&
    – SRB
    Nov 20, 2017 at 5:40
  • So this was not working if we have an associative array? Dec 10, 2017 at 9:57
  • No it doesn't , check loupax's answer for that
    – SRB
    Dec 11, 2017 at 11:05
34
function find_car_with_position($cars, $position) {
    foreach($cars as $index => $car) {
        if($car['Position'] == $position) return $index;
    }
    return FALSE;
}
2
  • 1
    excuse me, could i have some clarifications? the $position value is the value of Position while the $cars is the array itself? thank you for the reply Oct 8, 2011 at 4:52
  • 2
    SikretMiseon - yes. @diEcho - what "more easy" solution can you think of that wouldn't be very implementation-specific?
    – Amber
    Oct 8, 2011 at 5:39
24

You can try this

array_search(1, array_column($cars, 'position'));
14

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.

1
  • This was especially handy because I was looking for all the indices that contain a value, so all I had to do was drop the [0] at the end. The array_search('needle', array_column($haystack, 'column_key')); method only returns the first.
    – Ricca
    Oct 18, 2016 at 21:35
6

I basically 'recreated' underscore.js's findWhere method which is to die for.

The function:

function findWhere($array, $matching) {
    foreach ($array as $item) {
        $is_match = true;
        foreach ($matching as $key => $value) {

            if (is_object($item)) {
                if (! isset($item->$key)) {
                    $is_match = false;
                    break;
                }
            } else {
                if (! isset($item[$key])) {
                    $is_match = false;
                    break;
                }
            }

            if (is_object($item)) {
                if ($item->$key != $value) {
                    $is_match = false;
                    break;
                }
            } else {
                if ($item[$key] != $value) {
                    $is_match = false;
                    break;
                } 
            }
        }

        if ($is_match) {
            return $item;   
        }
    }

    return false;
}

Example:

$cars = array(
    array('id' => 1, 'name' => 'Toyota'),
    array('id' => 2, 'name' => 'Ford')
);

$car = findWhere($cars, array('id' => 1));

or

$car = findWhere($cars, array(
    'id' => 1,
    'name' => 'Toyota'
));

I'm sure this method could easily reduce LOC. I'm a bit tired. :P

2

actually all array functions are designed for single dimension array.You always need to keep in mind that you are applying it on single dimension array.

function find_car_with_position($cars, $position) {
    for($i=0;$i<count($cars);$i++){
        if(array_search($search_val, $cars[$i]) === false){
             // if value not found in array.....
        }  
        else{
            // if value is found in array....
        }
    }
}
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.