By using this site you agree to the use of cookies by Brugbart and our partners.

Learn more

Get Array Key and Value in PHP Foreach

How to get and use the array key and value in a PHP foreach loop.

Edited: 2013-04-24 21:45

You do not need to use any special functions to return the key of an array while looping it through, you can use the php foreach loop, which allows to easily access both the key and the value of the php array.

When you want to get the current array key in a foreach loop, all you have to do is to use the $array as $key=>$val syntax, your key will then be accessible as $key, and the value as $val.

The following demonstrates how to use the foreach loop of PHP.

$array = array();
$array['Hallo'] = 'Hallo Value';
$array['Hi'] = 'Hi Value';

foreach ($array as $key=>$val) {  
  echo $key .'->'.$val.'
'; }

So you do not have to use any specific function. This will work both on associative arrays and indexed arrays!

The above script will use foreach to loop through the array, and then assign the both the key and the value from the current array position to some variables. The names of the variables doesn't matter, you can name them as you do with you other variables!

More PHP Array Tutorials

  1. Finding Elements or Keys in Arrays
  2. Determine the Length of an Array
  3. Create an Array From a List of Keywords with Explode