Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,926 questions

51,859 answers

573 users

How to get a variable name as a string in PHP

3 Answers

0 votes
function get_variable_name($var) {
    foreach($GLOBALS as $variable_name => $value) {
        if ($value === $var) {
            return $variable_name;
        }
    }
 
    return false;
}
 
$num = 23452;
echo get_variable_name($num) . "\n";
 
$str = "PHP";
echo get_variable_name($str) . "\n";
 
$arr = array(1, 2, 3);
echo get_variable_name($arr) . "\n";
 
   
  
/*
run:
  
num
str
arr
  
*/

 



answered Jun 12, 2024 by avibootz
edited Jun 12, 2024 by avibootz
0 votes
function get_variable_name($var) {
    $trace = debug_backtrace();
    $this_file_source_code = file( __FILE__ );
    $the_line_code_that_call_to_this_function = $this_file_source_code[$trace[0]['line'] - 1];

    // get function argument - the $var name
    preg_match( "#\\$(\w+)#", $the_line_code_that_call_to_this_function, $match); 
      
    return $match;
}
  
$num = 23452;
print_r(get_variable_name($num));
  
$str = "PHP";
print_r(get_variable_name($str));
  
$arr = array(1, 2, 3);
print_r(get_variable_name($arr));
  
    
   
/*
run:
  
Array
(
    [0] => $num
    [1] => num
)
Array
(
    [0] => $str
    [1] => str
)
Array
(
    [0] => $arr
    [1] => arr
)
   
*/

 



answered Jun 12, 2024 by avibootz
edited Jun 12, 2024 by avibootz
0 votes
function get_variable_name($var) {
    $trace = debug_backtrace();
    $this_file_source_code = file($trace[0]['file']);
    $the_line_code_that_call_to_this_function  = $this_file_source_code[$trace[0]['line'] - 1];
    $pattern = '#(.*)'.__FUNCTION__.' *?\( *?(.*) *?\)(.*)#i';
    
    // get function parameter - the $var name
    $var  = preg_replace($pattern, '$2', $the_line_code_that_call_to_this_function);

    return trim($var);
}
 
$num = 23452;
echo get_variable_name($num) . "\n";
 
$str = "PHP";
echo get_variable_name($str) . "\n";
 
$arr = array(1, 2, 3);
echo get_variable_name($arr) . "\n";
 
   
  
/*
run:
 
$num
$str
$arr

*/

 



answered Jun 12, 2024 by avibootz

Related questions

2 answers 119 views
1 answer 254 views
1 answer 150 views
1 answer 124 views
1 answer 82 views
...