Skip to content
Advertisement

Using array_keys to search a multidimensional array with a partial array

$testArray = array( 
                array(1,2,"file1.png"), 
                array(1,3,"file2.png"), 
                array(1,4,"file3.png")                    
              );

print_r (array_keys($testArray, array(1,3, "file2.png"))); // Works
print_r (array_keys($testArray, array(1,3))); // Does not work.

As shown in the code above, I’d like to be able to quickly find an array in a multidimensional array but only specify two of the values.

Advertisement

Answer

One way to do this is to filter the testArray down to those number of keys using array_map, then use array_search to get the key.

$testArray = array( 
                array(1,2,"file1.png"), 
                array(1,3,"file2.png"), 
                array(1,4,"file3.png")                    
              );

$search = [1,3];
$filtered = array_map(function ($item) use ($search){
    return array_slice($item, 0, count($search));
}, $testArray);

$key = array_search($search, $filtered);
if ($key !== false){
    print_r($testArray[$key]);
} else {
    echo 'not found';
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement