How to access first level keys of a 2d array with a foreach loop? – Foreach

Photo of author
Written By M Ibrahim
altkey arrays cakephp foreach multidimensional-array

Quick Fix: Use a foreach loop with the array keys assigned as the loop variable, allowing direct access to the key-value pairs.

The Problem:

Given a two-dimensional array, the objective is to effectively utilize a foreach loop in PHP to access and display the first level keys (city names) of the array. The goal is to accomplish this within a view code, enabling you to iterate through the array and print the city names as headings (h5 tags) followed by respective place names as subheadings (h6 tags) for each city.

The Solutions:

Solution 1: Use Correct Syntax

To access the first level keys of a 2D array using a foreach loop, you need to use the correct syntax. The correct syntax is “`foreach ($array as $key => $value)“`, where `$key` will contain the key of the current element, and `$value` will contain the value of the current element. In your case, you can use the following code to access the first level keys of the `$places` array:

foreach ($places as $siteKey => $site) {
  echo "Site: $siteKey<br>";
}

This code will print the following output:

Site: Philadelphia

You can then use a nested foreach loop to access the individual elements of each site:

foreach ($places as $siteKey =&gt; $site) {
  echo "Site: $siteKey<br>";
  foreach ($site as $placeKey =&gt; $place) {
    echo "  Place: $place[$placeKey]<br>";
  }
}

This code will print the following output:

Site: Philadelphia
  Place: XYX
  Place: YYYY

Solution 2: Iterating over first level keys of a 2D array with a foreach loop

To access the first-level keys from a two-dimensional array with a foreach loop, you can use the following approach:


foreach ($array as $key => $value) {
    // $key will give you the first-level key
    // $value will give you the corresponding value associated with the key
}

In your specific example, you can modify your code in the following way to access the first-level keys of the $places array:


foreach ($places as $siteKey => $site) {
    echo "
$siteKey
"; foreach ($site as $place) { echo "
{$place['place_name']}
"; } }

With this modification, the $siteKey variable will give you the first-level keys (e.g., “Philadelphia”), and you’ll be able to access the inner array elements as you were doing before.

Additionally, you can also use a recursive function to iterate through multi-dimensional arrays. Here’s an example:


function displayArray($array) {
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            displayArray($value);
        } else {
            echo "Key: $key, Data: $value
"; } } } $places = [ 'Philadelphia' => [ ['place_name' => 'XYZ', 'place_id' => 103200, 'place_status' => 0], ['place_name' => 'YYYY', 'place_id' => 232323, 'place_status' => 0] ] ]; displayArray($places);

When you call displayArray($places), it will recursively traverse the array and print out the key-value pairs.

Solution 3: Using `array_keys()`

You can also leverage the `array_keys()` function to tackle this challenge.

Implementation:

  1. Fetch the keys of the 2D array using `array_keys($arrayToWalk)`.
  2. Determine the size of the array with `count($arrayToWalk)`. Let’s call this value `$arraySize`.
  3. Utilize `for` loop to iterate through the keys.
  4. Inside the loop, display the key and corresponding value using `echo ‘<option value="’ . $keys[$i] . ‘">’ . $arrayToWalk[$keys[$i]] . ‘</option>’;`.

In this solution, we employ the tried-and-tested `array_keys()` approach to retrieve the first level keys. Then, we iterate over these keys using a `for` loop and access the corresponding values from the 2D array through `$arrayToWalk[$keys[$i]]`. The values are then displayed as you intended.

Solution 4: {title}

To access the first-level keys of a two-dimensional array (`$places`) using a `foreach` loop, you can use the following approach:

foreach ($places as $siteKey => $siteValue) {
    // $siteKey is the key for the current top-level array
    // $siteValue is the array containing the subarray with data for each location

    // Display the top-level key (city name)
    echo "<h5>$siteKey</h5>";

    // Loop through the subarray to access the nested data
    foreach ($siteValue as $place) {
        // $place is an array with data for a single location within the city

        // Display the 'place_name' for the current location
        echo "<h6>{$place['place_name']}</h6>";
    }
}

This code provides a more straightforward and readable way to iterate through the $places array and specifically access the first-level keys (city names) and the nested data within each subarray.