PHP

Recursively Search for a Value in a Multi-Dimensional Array

Implement a recursive function to search for a specific value deep within a nested multi-dimensional array, useful for complex data structures.

<?php
$data = [
    'user_id' => 123,
    'profile' => [
        'name' => 'Jane Doe',
        'settings' => [
            'theme' => 'dark',
            'notifications' => [
                'email' => true,
                'sms' => false
            ]
        ]
    ],
    'permissions' => ['admin', 'editor', 'viewer'],
    'empty_array' => []
];

/**
 * Recursively searches for a specified needle in a multi-dimensional haystack array.
 * @param mixed $needle The value to search for.
 * @param array $haystack The array to search within.
 * @return bool True if the needle is found, false otherwise.
 */
function recursiveArraySearch(mixed $needle, array $haystack): bool {
    foreach ($haystack as $key => $value) {
        if ($value === $needle) {
            return true; // Value found at current level
        }
        if (is_array($value) && !empty($value) && recursiveArraySearch($needle, $value)) {
            return true; // Value found in a nested array
        }
    }
    return false; // Value not found
}

// Test cases
$foundTrue = recursiveArraySearch(true, $data);
echo "Found true: " . ($foundTrue ? 'Yes' : 'No') . "
"; // Expected: Yes

$foundEditor = recursiveArraySearch('editor', $data);
echo "Found editor: " . ($foundEditor ? 'Yes' : 'No') . "
"; // Expected: Yes

$foundSMS = recursiveArraySearch(false, $data);
echo "Found false (for SMS): " . ($foundSMS ? 'Yes' : 'No') . "
"; // Expected: Yes

$foundNonExistent = recursiveArraySearch('nonexistent_value', $data);
echo "Found 'nonexistent_value': " . ($foundNonExistent ? 'Yes' : 'No') . "
"; // Expected: No

$foundUserId = recursiveArraySearch(123, $data);
echo "Found user_id 123: " . ($foundUserId ? 'Yes' : 'No') . "
"; // Expected: Yes
?>
How it works: The `recursiveArraySearch` function provides a way to check if a specific value exists anywhere within a multi-dimensional array, no matter how deeply nested. It iterates through the array and, if it encounters another array, it calls itself recursively, effectively traversing the entire structure until the value is found or all possible paths are exhausted. This is invaluable for dealing with complex data structures where the exact depth of a value is unknown.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs