How can you efficiently extract specific values from nested arrays in PHP?

When dealing with nested arrays in PHP, you can efficiently extract specific values by using a recursive function that traverses through the nested arrays until the desired value is found. This approach allows you to access specific elements within the nested arrays without having to manually iterate through each level.

function recursiveArraySearch($array, $searchValue) {
    foreach($array as $key => $value) {
        if(is_array($value)) {
            $result = recursiveArraySearch($value, $searchValue);
            if($result !== null) {
                return $result;
            }
        } else {
            if($value === $searchValue) {
                return $value;
            }
        }
    }
    return null;
}

$nestedArray = [
    'key1' => 'value1',
    'key2' => [
        'key3' => 'value2',
        'key4' => [
            'key5' => 'value3'
        ]
    ]
];

$searchValue = 'value3';
$result = recursiveArraySearch($nestedArray, $searchValue);

if($result !== null) {
    echo "Found value: " . $result;
} else {
    echo "Value not found";
}