0

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?

1
  • $vname = $key; is been overwritten everytime Commented May 25, 2011 at 22:15

3 Answers 3

5

It is not possible to retrieve the "names" array1, array2, array3 from an array created with array($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').

0
1

Make the original array an associative array:

$container = array(
  'array1' => $array1,
  'array2' => $array2,
  'array3' => $array3
);

Then just print out the keys:

foreach($container as $name => $anArray){
  echo $name; //output: array1 array2 array3
}
1

I need to output: array1 array2 array3

You can't get name of variable in runtime. Don't waste your time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.