Search code examples
phparraysmultidimensional-arrayfilter

Filter rows of a 2d array which contain two specified column values


$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.


Solution

  • 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';
    }