172

How do I access the first level key of a two-dimensional array using a foreach loop?

I have a $places array like this:

[Philadelphia] => Array
        (
            [0] => Array
                (
                    [place_name] => XYX
                    [place_id] => 103200
                    [place_status] => 0
                )

            [1] => Array
                (
                [place_name] => YYYY
                [place_id] => 232323
                [place_status] => 0
            )

This is my view code that loops over the array:

<?php foreach($places as $site): ?>
    <h5><?=key($site)?></h5>
        <?php foreach($site as $place): ?>
            <h6><?=$place['place_name']?></h6>
        <?php endforeach?>

<?php endforeach ?>

Where I call key($site), I want to get Philadelphia, but I am just getting place_name from each row.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
matthewb
  • 3,462
  • 8
  • 37
  • 53

4 Answers4

475

You can access your array keys like so:

foreach ($array as $key => $value)
Pekka
  • 442,112
  • 142
  • 972
  • 1,088
44

As Pekka stated above

foreach ($array as $key => $value)

Also you might want to try a recursive function

displayRecursiveResults($site);

function displayRecursiveResults($arrayObject) {
    foreach($arrayObject as $key=>$data) {
        if(is_array($data)) {
            displayRecursiveResults($data);
        } elseif(is_object($data)) {
            displayRecursiveResults($data);
        } else {
            echo "Key: ".$key." Data: ".$data."<br />";
        }
    }
}
Phill Pafford
  • 83,471
  • 91
  • 263
  • 383
14

You can also use array_keys() . Newbie friendly:

$keys = array_keys($arrayToWalk);
$arraySize = count($arrayToWalk); 

for($i=0; $i < $arraySize; $i++) {
    echo '<option value="' . $keys[$i] . '">' . $arrayToWalk[$keys[$i]] . '</option>';
}
Melih Yıldız'
  • 415
  • 5
  • 17
  • 1
    Simpler more efficient code once you have `$keys`: `foreach ($keys as $key) ... $key ... $arrayToWalk[$key] ...` This is useful when `$keys` might be only a few of the keys in the array - otherwise `foreach ($arrayToWalk as $key => $value) ...` is both easier to use and slightly faster. – ToolmakerSteve Dec 03 '20 at 00:09
9
foreach($shipmentarr as $index=>$val){    
    $additionalService = array();

    foreach($additionalService[$index] as $key => $value) {

        array_push($additionalService,$value);

    }
}
Sam
  • 4,437
  • 11
  • 40
  • 59
kumar
  • 99
  • 1
  • 1