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

In PHP, getting a variable name as a string is useful for debugging and dynamic programming. There are several approaches to retrieve variable names, each with different use cases and limitations.

Using Variable Variables

The simplest approach uses PHP's variable variables feature to demonstrate the relationship between variable names and their string representations ?

<?php
$a = "This is it!";
$$a = "Demo string!";
print($a);
?>

This will produce the following output ?

This is it!

Using $GLOBALS Array

A more practical approach searches through the $GLOBALS array to find a variable by its value and return its name ?

<?php
$val = "This is it!";

function getVariableName($var) {
    foreach($GLOBALS as $name => $value) {
        if ($value === $var) {
            return $name;
        }
    }
    return false;
}

echo getVariableName($val);
?>

This will produce the following output ?

val

Using Compact Function

The compact() function can help create arrays with variable names as keys ?

<?php
$username = "john";
$email = "john@example.com";

$variables = compact('username', 'email');
print_r(array_keys($variables));
?>

This will produce the following output ?

Array
(
    [0] => username
    [1] => email
)

Limitations

Note that these methods have limitations:

  • The $GLOBALS approach only works with global variables
  • Multiple variables with the same value will return the first match
  • Local variables inside functions are not accessible via $GLOBALS

Conclusion

While PHP doesn't provide direct variable name introspection, you can use $GLOBALS array searching or compact() function depending on your specific needs. These methods are primarily useful for debugging and dynamic variable handling.

Updated on: 2026-03-15T08:19:25+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements