I have an array of arrays in PHP and I want to access the variable-name of each array (as a string) inside the container array.
Have:
$container = array($array1, $array2, $array2);
Need:
foreach ($container as $anArray) {
{...some other code...}
echo variable_name($anArray); // output: array1 array2 array3
}
I’m trying to run a foreach loop to output the name of each array with functions like the following (suggested in the PHP manual):
function vname(&$var, $scope=false, $prefix='unique', $suffix='value') {
if($scope) $vals = $scope;
else $vals = $GLOBALS;
$old = $var;
$var = $new = $prefix.rand().$suffix;
$vname = FALSE;
foreach($vals as $key => $val) {
if($val === $new) $vname = $key;
}
$var = $old;
return $vname;
}
But that function understandably only outputs: anArray (x3)
I need to output: array1 array2 array3
Any suggestions?
It is not possible to retrieve the “names”
array1,array2,array3from an array created witharray($array1, $array2, $array3). Those variable names are gone.You can make the array keys the names though:
array('array1' => $array1, 'array2' => $array2, 'array3' => $array3)A shortcut for this is
compact('array1', 'array2', 'array3').