php: find a value in multidimensional array

2019-08-03 2019-12-30 00:42:03 PHP,array,EN

Q: given a multidimensional array. how can i find a value in it ?

A: use the php function array_search in conjunction with array_column to solve this.

usage example

$aData = [
    'aKeyValue' => [
        0 => [
                'sKey' => 'sOldname',
                'sValue' => '/media/foo.txt',
            ],
        1 => [
                'sKey' => 'sNewname',
                'sValue' => '/media/bar.txt',
            ],
        2 => [
                'sKey' => 'sStatus',
                'sValue' => 'done',
            ],
        3 => [
                'sKey' => 'bMoveSuccess',
                'sValue' => true,
            ],
        4 => [
                'sKey' => 'aMessage',
                'sValue' => 'The owls are not what they seem',
            ]
    ]
];

// this will give key: int(3)
var_dump(
    array_search(

        // what to search for
        'bMoveSuccess',

        // Array to search in & Key to look after
        array_column($aData['aKeyValue'], 'sKey')
    )
);

This website uses Cookies to provide you with the best possible service. Please see our Privacy Policy for more information. Click the check box below to accept cookies. Then confirm with a click on "Save".