PHP get both array value and array key PHP get both array value and array key arrays arrays

PHP get both array value and array key


This should do it

foreach($yourArray as $key => $value) {    //do something with your $key and $value;    echo '<a href="' . $value . '">' . $key . '</a>';}

Edit: As per Capsule's comment - changed to single quotes.


For some specific purposes you may want to know the current key of your array without going on a loop. In this case you could do the following:

reset($array);echo key($array) . ' = ' . current($array);

The above example will show the Key and the Value of the first record of your Array.

The following functions are not very well known but can be pretty useful in very specific cases:

key($array);     //Returns current keyreset($array);   //Moves array pointer to first recordcurrent($array); //Returns current valuenext($array);    //Moves array pointer to next record and returns its valueprev($array);    //Moves array pointer to previous record and returns its valueend($array);     //Moves array pointer to last record and returns its value


Like this:

$array = array(    'Google' => 'http://google.com',    'Facebook' => 'http://facebook.com');foreach($array as $title => $url){    echo '<a href="' . $url . '">' . $title . '</a>';}