How to get a variable name as a string in PHP?
In this tutorial, we’re going to see how to get the name of a variable by accessing get_defined_vars().
There is no predefined function in PHP that can output the name of a variable. However, you can use the result of get_defined_vars(), which returns all the variables defined in the scope, including name and value.
Definition of your own function
<?php // Function for determining the name of a variable function getVarName(&$var, $definedVars=null) { $definedVars = (!is_array($definedVars) ? $GLOBALS : $definedVars); $val = $var; $rand = 1; while (in_array($rand, $definedVars, true)) { $rand = md5(mt_rand(10000, 1000000)); } $var = $rand; foreach ($definedVars as $dvName=>$dvVal) { if ($dvVal === $rand) { $var = $val; return $dvName; } } return null; } // the name of $a is to be determined. $a = 1; // Determine the name of $a echo getVarName($a); ?>
Output:
a
[st_adsense]
The function getVarName() proceeds as follows:
- The variable for which the name is to be determined is received as a reference. This is important because the value must be adjusted below.
- The old value of the variable is saved.
- The value of the variable is temporarily changed to a random value that does not yet appear among the defined variables.
- The variable that has this random value is searched for among the defined variables.
- The value of this variable is reset to the saved value.
- The name of this variable is returned.
getVarName() in the scope of a function
In the previous example, the function was called in the global scope (top level). In this case, the result of get_defined_vars() does not have to be transferred, the function then automatically uses $GLOBALS. However, if you are in a function, then get_defined_vars() must be used once.
<?php // insert the getVarName function from the previous example here function myfunction() { $a = 1; var_dump(getVarName($a)); // this call does not find $a var_dump(getVarName($a, get_defined_vars())); // with this it will be found } myfunction(); ?>
Output:
a[st_adsense]