Skip to content
Advertisement

How to get a variable name as a string in PHP?

Say i have this PHP code:

$FooBar = "a string";

i then need a function like this:

print_var_name($FooBar);

which prints:

FooBar

Any Ideas how to achieve this? Is this even possible in PHP?

Advertisement

Answer

You could use get_defined_vars() to find the name of a variable that has the same value as the one you’re trying to find the name of. Obviously this will not always work, since different variables often have the same values, but it’s the only way I can think of to do this.

Edit: get_defined_vars() doesn’t seem to be working correctly, it returns ‘var’ because $var is used in the function itself. $GLOBALS seems to work so I’ve changed it to that.

function print_var_name($var) {
    foreach($GLOBALS as $var_name => $value) {
        if ($value === $var) {
            return $var_name;
        }
    }

    return false;
}

Edit: to be clear, there is no good way to do this in PHP, which is probably because you shouldn’t have to do it. There are probably better ways of doing what you’re trying to do.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement