1

Hi I want to create a function in which I can pass a variable and output the name of the variable and its value as a sting. Something like this:

$firstname = 'John';
$lastname = 'Doe';

echo my_function($firstname); // outputs: "Var name: firstname , has: John"
echo my_function($lastname);  // outputs:  "Var name: lastname , has: Doe"
ltdev
  • 4,037
  • 20
  • 69
  • 129
  • 1
    It can be done with [debug_backtrace()](http://www.php.net/manual/en/function.debug-backtrace.php), but isn't recommended as good or sensible coding practise..... what would you expect if the function was called with `echo my_function("JOHN");`? You want this for debug purposes, then use a real debugger – Mark Baker Mar 28 '15 at 10:05
  • might be related http://stackoverflow.com/questions/2876735/php-function-find-arguments-variable-name-and-function-calls-line-number – Kevin Mar 28 '15 at 10:08
  • This might help also: http://stackoverflow.com/questions/255312/how-to-get-a-variable-name-as-a-string-in-php – YyYo Mar 28 '15 at 10:26

2 Answers2

1

Take a look at get_defined_vars()

You can var_dump this and it will show all the variables you defined. You could then loop through and dump each ones value too.

http://php.net/get_defined_vars

Matt The Ninja
  • 2,641
  • 4
  • 28
  • 58
0

The only easiest way i can think of this time is make use of $GLOBAL

<?php
function my_function($val) {
  foreach($GLOBALS as $name => $value) {
      if ($value == $val) {
          return "Var name: ".$name." , has: ".$val."<br>";
      }
  }
}

$first = 'John';
$firstname = 'John';
$lastname = 'Doe';
echo my_function($firstname); // outputs: "Var name: firstname , has: John"
echo my_function($lastname);

Output:

Var name: firstname_my , has: John
Var name: lastname_my , has: Doe

Let say if there is 2 variables with same

$first = 'John';
$firstname = 'John';

You can modify your code to differentiate like this

function my_function($val) {
   foreach($GLOBALS as $name => $value) {
       if ($value == $val && substr($name,-3) == "_my") {
          return "Var name: ".$name." , has: ".$val."<br>";
       }
   }
}

$first = 'John';
$firstname_my = 'John';
$lastname_my = 'Doe';

echo my_function($firstname_my); // outputs: "Var name: firstname , has: John"
echo my_function($lastname_my);
Sasi Varunan
  • 2,806
  • 1
  • 23
  • 34