173

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.

0

4 Answers 4

480

You can access your array keys like so:

foreach ($array as $key => $value) 
Sign up to request clarification or add additional context in comments.

Comments

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 />"; } } } 

Comments

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>'; } 

1 Comment

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.
10
foreach($shipmentarr as $index=>$val){ $additionalService = array(); foreach($additionalService[$index] as $key => $value) { array_push($additionalService,$value); } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.