[php] How to loop through an associative array and get the key?

My associative array:

$arr = array(
   1 => "Value1",
   2 => "Value2",
   10 => "Value10"
);

Using the following code, $v is filled with $arr's values

 foreach($arr as $v){
    echo($v);    // Value1, Value2, Value10
 }

How do I get $arr's keys instead?

 foreach(.....){
    echo($k);    // 1, 2, 10
 }

This question is related to php loops associative-array

The answer is


 foreach($arr as $key=>$value){
    echo($key);    // key
 }

If you use array_keys(), PHP will give you an array filled with just the keys:

$keys = array_keys($arr);
foreach($keys as $key) {
    echo($key);
}

Alternatively, you can do this:

foreach($arr as $key => $value) {
    echo($key);
}

If you use nested foreach() function, outer array's keys print again and again till inner array values end.

<?php 

$myArray = ['key_1' => ['value_1', 'value12'],
            'key_2' => ['value_2', 'value22'], 
            'key_3' => ['value_3', 'value32']
           ];

$keysOfMyArray = array_key($myArray);

for ($x = 0; $x < count($myArray); $x++){
       print "\t".$keysOfMyArray[$x]."\t\t".implode("\t\t",$myArray[$keysOfMyArray[$x]]."\n");
}

?>

foreach($array as $k => $v)

Where $k is the key and $v is the value

Or if you just need the keys use array_keys()


Nobody answered with regular for loop? Sometimes I find it more readable and prefer for over foreach
So here it is:

$array = array('key1' => 'value1', 'key2' => 'value2'); 

$keys = array_keys($array);

for($i=0; $i < count($keys); ++$i) {
    echo $keys[$i] . ' ' . $array[$keys[$i]] . "\n";
}

/*
  prints:
  key1 value1
  key2 value2
*/

Use $key => $val to get the keys:

<?php

$arr = array(
    1 => "Value1",
    2 => "Value2",
    10 => "Value10",
);

foreach ($arr as $key => $val) {
   print "$key\n";
}

?>

<?php
$names = array("firstname"=>"maurice",
               "lastname"=>"muteti", 
               "contact"=>"7844433339");

foreach ($names as $name => $value) {
    echo $name." ".$value."</br>";
}

print_r($names);
?>

While arguably being less clear this method is faster by roughly a factor of roughly 3.5 (At least on the box I used to test)

$foo = array(
    1 => "Value1",
    2 => "Value2",
    10 => "Value10"
);
while($bar = each($foo)){
    echo $bar[0] . " => " . $bar[1];
}

I would imagine that this is due to the fact the foreach copies the entire array before iterating over it.


Oh I found it in the PHP manual.

foreach ($array as $key => $value){
    statement
}

The current element's key will be assigned to the variable $key on each loop.


The following will allow you to get at both the key and value at the same time.

foreach ($arr as $key => $value)
{
  echo($key);
}

I use the following loop to get the key and value from an associative array

foreach ($array as $key => $value)
{
  echo "<p>$key = $value</p>";
}

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to loops

How to increment a letter N times per iteration and store in an array? Angular 2 Cannot find control with unspecified name attribute on formArrays What is the difference between i = i + 1 and i += 1 in a 'for' loop? Prime numbers between 1 to 100 in C Programming Language Python Loop: List Index Out of Range JavaScript: Difference between .forEach() and .map() Why does using from __future__ import print_function breaks Python2-style print? Creating an array from a text file in Bash Iterate through dictionary values? C# Wait until condition is true

Examples related to associative-array

How to insert a new key value pair in array in php? Rename a dictionary key How to update specific key's value in an associative array in PHP? Is there a way to create key-value pairs in Bash script? PHP combine two associative arrays into one array Are there dictionaries in php? Display array values in PHP Adding an item to an associative array Extract subset of key-value pairs from Python dictionary object? Java associative-array