phparraysmultidimensional-arrayfilter

Find the first occurring array row which contains a search value and return the first level key


I have the following array:

Array
 (
[documents] => Array
    (
        [0] => application/pdf
        [1] => application/x-pdf
    )

[images] => Array
    (
        [0] => image/cgm
        [1] => image/g3fax
    )

[videos] => Array
    (
        [0] => video/dl
        [1] => video/fli
        [2] => video/gl
        [3] => video/mpeg
    )

And I have a couple of tables called documents, images, videos. So what I would like to do is to see in which database the file should go.

I tried to do it with array_search() but without success. After that I found a function which I tried also no luck.

function array_search_multi( $value, array $array ) {
    foreach( $array as $key => $val ) {
        if( is_array( $val ) ) {
            array_search_multi($value, $val); // Recursive in case array is deeper
        } else {
            if( $val === $value ) {
                return $key;
            }
        }
    }
    return false;
}

Solution

  • If I understand you're looking for something like this

    function find($mimeType) {
    
        $array = [
            'documents' => ['application/pdf','application/x-pdf'],
            'images'    => ['image/cgm','image/g3fax'],
            'videos'    => ['video/dl','video/fli','video/gl','video/mpeg'],    
        ];
    
        $table = null;
        foreach ($array as $type => $values) {
            $table = $type;
            if ( in_array ($mimeType, $values) ) break;
        }
        return $table;
    }
    
    $sample = 'image/g3fax';
    echo find($sample);