Say i have this PHP code:
$FooBar = \"a string\";
i then need a function like this:
print_var_name($FooBar);
This is the way I did it
function getVar(&$var) {
$tmp = $var; // store the variable value
$var = '_$_%&33xc$%^*7_r4'; // give the variable a new unique value
$name = array_search($var, $GLOBALS); // search $GLOBALS for that unique value and return the key(variable)
$var = $tmp; // restore the variable old value
return $name;
}
Usage
$city = "San Francisco";
echo getVar($city); // city
Note: some PHP 7 versions will not work properly due to a bug in array_search
with $GLOBALS
, however all other versions will work.
See this https://3v4l.org/UMW7V