Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get variable name in PHP?

Tags:

php

func($name1) should return name1

Is it possible?

like image 516
user198729 Avatar asked Dec 09 '22 17:12

user198729


1 Answers

Here's a function that does it.

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];
}

Call it like this

$test = "blah";
echo var_name($test,  get_defined_vars());

That will print out "test".

I originally found that function over here You can also do it by iterating over the array returned by get_defined_vars(). That might be a bit easier to understand.

like image 115
andyjdavis Avatar answered Dec 23 '22 22:12

andyjdavis