Home >Backend Development >PHP Tutorial >How to Access First Level Keys of a 2D Array Using a Foreach Loop?
Accessing the First Level Keys of a 2D Array Using a Foreach Loop
To obtain the city names in the $places array, you can access the first level keys. A straightforward method is through a foreach loop.
In your PHP code:
<code class="php">foreach ($places as $city => $sites) { echo "<h5>{$city}</h5>"; foreach ($sites as $site) { echo "<h6>{$site['place_name']}</h6>"; } }</code>
This code iterates over the keys of the outer array, which are the city names. Within the inner loop, it accesses the first level keys as $city. By using =>, you assign both the key and value to the corresponding variables, allowing you to access the city name directly as $city.
The above is the detailed content of How to Access First Level Keys of a 2D Array Using a Foreach Loop?. For more information, please follow other related articles on the PHP Chinese website!