PHP tutorial logoA PHP quick tip on something I keep on forgetting. Now while the foreach functionality is great in iterating through an array and returning the array’s values, sometimes one wishes to also capture the key against which a particular value is stored and for this one should use the overloaded form of the foreach function (usually foreach ($arr as $value) ), namely:

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

This returns two variables in the form of $key which is the actual key name used for the array item and $value which is the actual value stored for that particular array item.


If you want to test it out for yourself, simply plug an array of your own making into this little blob of code: 

foreach ($arr as $key => $value) {
    echo "Key: $key; Value: $value<br />n";