Sunday, November 23, 2025
HomeLanguagesHow to get a variable name as a string in PHP?

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

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 global scope. It is an associative array which contains the reference of all variables which are currently defined in the global scope.

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




<?php
  
// Declare and initialize a variable
$test = "This is a string";
  
// Function that returns the variable name
function getVariavleName($var) {
    foreach($GLOBALS as $varName => $value) {
        if ($value === $var) {
            return $varName;
        }
    }
    return;
}
  
// Function call and display the
// variable name
print getVariavleName($test);
  
?>


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.




<?php
  
// Declare and initialize a variable
$name = "test";
  
// Reference variable to store string
$$name = "This is a string";
  
// Display result
print($name);
  
?>


Output:

test
RELATED ARTICLES

Most Popular

Dominic
32407 POSTS0 COMMENTS
Milvus
97 POSTS0 COMMENTS
Nango Kala
6785 POSTS0 COMMENTS
Nicole Veronica
11932 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12000 POSTS0 COMMENTS
Shaida Kate Naidoo
6907 POSTS0 COMMENTS
Ted Musemwa
7168 POSTS0 COMMENTS
Thapelo Manthata
6864 POSTS0 COMMENTS
Umr Jansen
6852 POSTS0 COMMENTS