If you can store your variables like this:
$array = array(
'a' => 'apple',
'b' => 'banana',
'c' => 'carrot',
'd' => 'date',
'e' => 'elephant');
You can use the key
function to retrieve the index/key for the current array element inside any type of loop, see #1, or use the key => value
syntax in your foreach()
loop, see #2:
<?php
$array = array(
'a' => 'apple',
'b' => 'banana',
'c' => 'carrot',
'd' => 'date',
'e' => 'elephant');
/* #1 */
foreach($array as $value) {
/* get the key for the item at the cursor position of the array */
$key = key($array);
print "{$key} = {$value}<br>";
/* move the cursor to the next item in the array */
next($array);
}
/* #2 */
foreach($array as $key => $value) {
print "{$key} = {$value}<br>";
}
?>
If you are simply trying to get a variable name, you can not store the values in an array and maintain the variable names, once you put the values into the array, they lose the variable name.
Outside of an array, you can use the following solution (from http://www.php.net/manual/en/language.variables.php#76245):
<?
$myVarName = "myValue";
echo var_name($myVarName) . " = {$myVarName}";
function var_name(&$var, $scope=0)
{
$old = $var;
if (($key = array_search($var = 'unique'.rand().'value', !$scope ? $GLOBALS : $scope)) && $var = $old) return $key;
}
?>