How can nested arrays or objects in PHP be properly iterated through to access specific values?

When dealing with nested arrays or objects in PHP, you can properly iterate through them using nested loops or recursive functions. By recursively iterating through each level of the nested structure, you can access specific values deep within the array or object.

<?php
// Function to recursively iterate through nested arrays or objects
function recursiveIterate($data) {
    foreach ($data as $key => $value) {
        if (is_array($value) || is_object($value)) {
            // If value is an array or object, recursively call the function
            recursiveIterate($value);
        } else {
            // Access specific values here
            echo "$key: $value\n";
        }
    }
}

// Example nested array
$nestedArray = [
    'key1' => 'value1',
    'key2' => [
        'subkey1' => 'subvalue1',
        'subkey2' => 'subvalue2'
    ],
    'key3' => 'value3'
];

// Call the function with the nested array
recursiveIterate($nestedArray);
?>