VOOZH about

URL: https://www.geeksforgeeks.org/php/how-to-get-a-variable-name-as-a-string-in-php/

⇱ How to get a variable name as a string in PHP? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 17 Jul, 2024

Use variable name as a string to get the variable name. There are many ways to solve this problem some of them are discussed below:

Method 1: Using $GLOBALS:

It is used to reference all variables available in the global scope. It is an associative array containing the reference of all variables currently defined in the global scope.

Example: This example uses $GLOBAL reference to get the variable name as a string.


Output
test

Method 2: Using $$ Operator

The $$var_name is known as reference variable where $var_name is a normal variable. The $$var_name used to refer to the variable with the name as value of the variable $var_name.

Example:This example uses $$ operator to get the variable name as a string.


Output
test

Using debug_backtrace()

Using debug_backtrace() in PHP, you can extract a variable name from the debug information. This involves reading the specific line of code where the function was called.

Example


Output
varName

Using get_defined_vars() and array_search()

The get_defined_vars() function returns an array of all defined variables, both local and global. By searching this array, we can find the key (variable name) corresponding to a given value.

Example:


Output
The variable name of exampleVar is: var
The variable name of anotherVar is: var
Comment
Article Tags: