How to Get a Variable Name as a String in PHP

admin_img Posted By Bajarangi soft , Posted On 03-12-2020

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. 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.

variable name as a string

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

<?php

// Declare and initialize a variable php

$test="this is 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);
?>
 

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


<?php
  
// Declare and initialize a variable 
$name="text";

// Reference variable to store string 
 $name="this is a string";

 // Display result
  print($name);
  ?>

Related Post