phparraysmultidimensional-array

"Wildcard" key with foreach PHP


I have an array that looks like this:

$array = Array(
    "person1" => Array(
        "person2" => Array(
            "something", "something else", "something else again"),
        "person3" => Array(
            "hey", "hi", "hello")
    ),
    "person4" => Array(
        "person5" => Array(
            "bob", "bill", "bobby", "billy"),
        "person6" => Array(
            "there", "their", "here")
    )
); 

I have a foreach loop that looks like this:

foreach($array["person1"] as $value){
}

I want to get to the third level of the array (with all the words like "something"). There's a key that I don't know ("person2" or "person3") Is there a "wildcard" I can use as the key? (Like $array["person1"][wildcard][0]?


Solution

  • There are no "wildcards" for array keys, since the keys are identifiers.

    Simply iterate through the array and echo the first element:

    foreach ($array['person1'] as $key => $items) {
        // $key will contain the key, if you would need it.
        // $items contains the array of each child
        echo $items[0] . '<br />';
    }