Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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
$GLOBALSapproach 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.
