SuperDJ
SuperDJ

Reputation: 7661

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

Upvotes: 0

Views: 84

Answers (2)

mickmackusa
mickmackusa

Reputation: 47864

Use PHP8.4 's array_find_key() with in_array() to find the first occurring match and return the first level key. Demo

$array = [
    'documents' => ['application/pdf','application/x-pdf'],
    'images'    => ['image/cgm','image/g3fax'],
    'videos'    => ['video/dl','video/fli','video/gl','video/mpeg'],    
];

$find = 'image/g3fax';

var_export(
    array_find_key(
        $array,
        fn($row) => in_array($find, $row)
    )
);

Upvotes: 0

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);

Upvotes: 1

Related Questions