e-Planet

November 18, 2005

How to get a variable name as a string in PHP

PHP - Jean-Jacques Guegan

On rare occasions, you may need to retrieve a variable name as a string.

This handy little function retreives the name of the variable:

 
<?php
      $my_var = 1;
      echo var_name ($my_var);
?>
 

will give 'my_var'.

I started trying to find a solution to this problem, because I needed such a function and because questions about it appeared on several mailing lists and forums:
[PHP] Is there a way to get a variable name as a string?

most people said it was not possible...
Re: [PHP] Is there a way to get a variable name as a string?
From: Rasmus Lerdorf

In PHP it is possible to use a variable if you have its name as a string :

 
<?php
 
    $iVarName = 'MaxSize';
    $$iVarName = 10;
    echo $MaxSize;
 
?>
 

But PHP does not natively include a way to get the name of a given variable.

This might be useful in situations where you design a function with a parameter passed by reference and you need to know which variable was sent as a parameter for this function.

 

The solution :

The following function retreives the variable name from a given variable:

 
<?php
 
function var_name (&$iVar, &$aDefinedVars)
    {
    foreach ($aDefinedVars as $k=>$v)
        $aDefinedVars_0[$k] = $v;
 
    $iVarSave = $iVar;
    $iVar     =!$iVar;
 
    $aDiffKeys = array_keys (array_diff_assoc ($aDefinedVars_0, $aDefinedVars));
    $iVar      = $iVarSave;
 
    return $aDiffKeys[0];
    }
 
?>
 

This function has to be called with a second parameter always set to the result of the function "get_defined_vars()":

 
<?php	
 
var_name($iVar, get_defined_vars());
 
?>
 

 

How does it work ?

var_name compares the result of the function "get_defined_vars()" before and after modification of the variable whose name we want to find.

The initial set of defined variables passed as a parameter to var_name is first stored in "$aDefinedVars_0" and compared later.

Before modifying the value of the variable, its value is saved in $iVarSave.

$iVar is then changed to something different :
$iVar=!$iVar;

$aDefinedVars keeps track of this modification and can be compare to $aDefinedVars_0 (its initial value). The difference is the variable we modified and we can get its name as a string in the key value of the array record.

The value of the variable is restored to its initial value kept in $iVarSave and the name of the variable is returned.

 

Example :

The following PHP code shows the function var_name in action:

 
<?php
 
$v_1 = 1;                               echo 'var $<b>',var_name ($v_1, get_defined_vars()),'</b> = ',var_dump($v_1),'<br>';
$v_2 = 4;                               echo 'var $<b>',var_name ($v_2, get_defined_vars()),'</b> = ',var_dump($v_2),'<br>';
$v_3 = 'qwerty';                        echo 'var $<b>',var_name ($v_3, get_defined_vars()),'</b> = ',var_dump($v_3),'<br>';
$v_4 = array('aa'=>'11','bb'=>'22',3);  echo 'var $<b>',var_name ($v_4, get_defined_vars()),'</b> = ',var_dump($v_4),'<br>';
$v_5 = &$v_2;                           echo 'var $<b>',var_name ($v_5, get_defined_vars()),'</b> = ',var_dump($v_5),'<br>';
                                        echo 'var $<b>',implode ('</b> / $<b>',var_name ($v_5, get_defined_vars(),true)),'</b> = ',var_dump($v_5),'<br>';
 
function test()
    {
    $v_1 = 'qwerty';                    echo 'var $<b>',var_name ($v_1, get_defined_vars()),'</b> = ',var_dump($v_1),'<br>
<hr>';
    global $v_5;                 echo 'var $<b>',var_name ($v_5, get_defined_vars()),'</b> = ',var_dump($v_5),'<br>
<hr>';
    }
 
test();
 
?>
 

var_name can retreive the name of the variable in every case.

 

Application :

The most direct application of this function is, of course, a "dump" function.
Just call this "dump" function with the variable you want to monitor - do not forget to add the "get_defined_vars()" parameter...

 
<?php	
 
function dump(&$v, &$aDefinedVars)
    {
    echo '
<pre>$<b>',implode ('</b> / $<b>',var_name ($v, $aDefinedVars, true)),'</b> = ',print_r($v, true),'</ pre><br>
<hr>';
    }
 
dump($v_4, get_defined_vars());
 
?>
 

 

Going further :

The function var_name can be enhanced by adding the parameter $bShowAllRef to show, if set to true, all the references relating to the variable passed as a parameter:

 
<?php
 
function var_name (&$iVar, &$aDefinedVars, $bShowAllRef=false )
    {
    foreach ($aDefinedVars as $k=>$v)
        $aDefinedVars_0[$k] = $v;
 
    $iVarSave = $iVar;
    $iVar     =!$iVar;
 
    $aDiffKeys = array_keys (array_diff_assoc ($aDefinedVars_0, $aDefinedVars));
    $iVar      = $iVarSave;
 
    return ($bShowAllRef? $aDiffKeys: $aDiffKeys[0]);
    }
 
?>
 

That's it ! You can download the function here.

This code is free to use and published under the GPL license.

 
 
 
 
 
 

8 Comments »

  1. [...] este faptul ca internetul nu prezinta o rezolvare a acesteia, sau e foarte greu de gasit. Totusi, cineva a abordat problema intr-un mod ingenios, care va fi prezentat mai jos. Acesta s-a folosit de o [...]

    Pingback by Cum sa extragi numele unei variabile in PHP? | WorldIT — July 18, 2010 @ 9:19 am

  2. Good Done!

    Comment by shafy — August 10, 2010 @ 6:39 am

  3. Works only when there are no class objects - catchable fatal error otherwise

    Comment by youlleck — August 12, 2010 @ 7:23 pm

  4. Thanks for sharing.
    I trying to find a way to do the samething you have done. I choose to use php extension. then I find your solution. It works great. but the other day I found It can’t work like:

    $a = 10;
    $b =&$a;

    var_name($b, get_defined_vars()); // a instead of a.

    Comment by reeze — November 5, 2010 @ 3:36 am

  5. Impressive.

    Comment by Yehia — January 11, 2011 @ 12:04 pm

  6. You can do it by converting the variable to a key/value set before passing it to the function.

    function varName($theVar) {
    $variableName = key($theVar);
    $variableValue = $theVar[$variableName];
    echo (’The name of the variable used in the function call was ‘.$variableName.”);
    echo (’The value of the variable used in the function call was ‘.$variableValue.”);
    }
    $myVar = ‘abc’;
    varName(compact(’myVar’));

    Though I don’t recommend creating a reference to a nameless variable, `function varName(&$theVar)` works too.

    Since compact() takes the variable name as a string rather than the actual variable, iterating over a list of variable names should be easy.

    As to why you would want to do this — don’t ask me but it seems like a lot of people ask the question so here’s my solution.

    Comment by EngineerGreg — February 3, 2011 @ 12:33 am

  7. [...] http://mach13.com/how-to-get-a-variable-name-as-a-string-in-php [...]

    Pingback by How to get a variable name as a string in PHP - Making stuff work - Tech Notes — February 3, 2011 @ 4:07 am

  8. for comments #6 and #7

    First I was excited to see how your solution works.

    After some tries, I realized that “compact” is of complete no use here…

    You have to enter the variable name as a string parameter… to finally get this variable name…

    a simple
    function varName($theVarName) { return $theVarName; }
    does the same. :(

    Problem is to enter the variable itself as a parameter to get its name.

    Comment by admin — February 3, 2011 @ 9:23 am

RSS feed for comments on this post. TrackBack URI

Leave a comment

 
Powered by WordPress
Copyright Mach13