[thelist] get name of variable variable in PHP

Juha Suni juha.suni at sparecom.fi
Wed Sep 27 09:53:35 CDT 2006

Sarah Adams wrote:
> I'm working on some code that uses PHP's "variable variables" [0] and
> in the process of debugging, I'd really like to be able to print out
> not just the value but the *name* of a variable variable (e.g. in a
> loop, where it might not be obvious exactly which variable variable
> is the one being debugged). Is there some function that will allow me
> to do this?

Found this handy function for just this purpose in the comments of the 
variables section of the PHP manual (www.php.net/variables):

  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;

Original author is lucas dot karisny at linuxmail dot org. In the comment he 
also offers a further explanation to its use and why it works as it does. 
For basic use, you just call it with the variable as the parameter, and it 
returns the name. Worked flawless with quick testing.



More information about the thelist mailing list