-3

how can i print var name instead var value in php? Like this code:

$Tree = "abcd";
$str = "zwd";

i want to print something like this: tree = abcd str = zwd

please help me

Ebrahim
  • 13
  • 4
  • 5
    of what possible use would this be?vars only exist because YOU wrote them. The only time you'd have arbitrary variable names is if you're doing (stupid) stuff like `extract()`, have `register_globals` on, or are using variable variables. – Marc B Oct 21 '16 at 15:55
  • 6
    Possible duplicate of [How to get a variable name as a string in PHP?](http://stackoverflow.com/questions/255312/how-to-get-a-variable-name-as-a-string-in-php) – HPierce Oct 21 '16 at 15:55
  • this could be related to this post: [how-to-get-a-variable-name-as-a-string-in-php](http://stackoverflow.com/questions/255312/how-to-get-a-variable-name-as-a-string-in-php) – Rui Silva Oct 21 '16 at 16:00

4 Answers4

3

You may want to take a look at compact function

<?php
    $city  = "San Francisco";
    $state = "CA";
    $event = "SIGGRAPH";

    $location_vars = array("city", "state");

    $result = compact("event", "nothing_here", $location_vars);
    // print_r($result);
?>

Then print the key and its value,

foreach($result as $key => $value)
{
    echo $key . " : " . $value;
}
rakibtg
  • 5,521
  • 11
  • 50
  • 73
2

What you maybe looking for is

echo 'Tree = ' . $Tree;
echo '<br>';
echo 'str = ' . $str;

I am pretty sure OP meant above, btw for expert level programmers, Why this question is paradoxical in nature, is lets say you want to print/output the name of variable $xyz. See....

...did you notice...

....that in order to print the name of a variable you had to actually type the name of the variable in the first place! How else would you refer to that variable!!! And for that the above method of concatenation is best suited :)

Here someone with sane mentality tried to explain better.

Community
  • 1
  • 1
Mohd Abdul Mujib
  • 13,071
  • 8
  • 64
  • 88
1

I think what you want is this:

$array = array('Tree' => 'abcd', 'str' => 'zwd');
foreach ($array as $name => $value) {
    echo $name . ' = ' . $value;
}
Vinicius Dias
  • 664
  • 3
  • 15
-1

If you want to print variable names not writing it by yourself you should use get_defined_vars() as follow :

$var1 = 'I am ';
$what = array_search($var1, get_defined_vars(), true);

printf($var1.'%s', $what); // I am var1
carte-sd
  • 21
  • 4
  • 1
    1. You may have more than one variable with the same value, 2. you’re already writing `$var1`, why bend over backwards like this instead of just hardcoding the name‽ – deceze Mar 05 '19 at 07:09
  • If there is 2 variables with the same value then you will have to handle 2 differents results. Personnally, I would never do such a thing, I'm just answering the question : there is no other way to get a variable name without writing its name by yourself. – carte-sd Mar 05 '19 at 08:39