views:

312

answers:

6

Explain this interview question to me...

Q: If the variable $a is equal to 5 and variable $b is equal to character a, what’s the value of $$b?

A: 100, it’s a reference to existing variable.

A: 
  $$b - 100
= $a - 100 // substituting $b=a
= 5 - 100
= -95
codaddict
+8  A: 

That's a variable variable. PHP will look up the variable with the name stored in the string $b. So if $b == 'a' then $$b == $a.

It's a lot like pointers in C, except they use variable name strings instead of memory addresses to point to each other. And you can dereference as many times as you want:

$a = 5;
foreach (range('b', 'z') as $L) {
  $$L = chr(ord($L) - 1);
}
echo $$$$$$$$$$$$$$$$$$$$$$$$$$z;

Output:

5
yjerem
beautiful......
Stefano Borini
@Stefano: that's one word for it...
nickf
Murali might be blank about this, but the xample is awesome...
OM The Eternity
A: 

I don't know if the '?' is erroneous in the statement '$$b? - 100' but I don't think that will compile.

However:

$a = 5
$b = 'a';
$c = $$b - 100;

$c will equal -95, because $$b is a variable variable reference and given that $a = 5 it resolves to $a (5) - 100, or -95.

mkgrunder
`$$b` is perfectly legal syntax
webdestroya
@webdestroya but `$$b?` is not
Mike B
Yes I was referring to the '?' character from the '$$b? - 100' part of the question. :)
mkgrunder
@Mike B But `$$b?'foo':'bar'` would be. :o)
deceze
@deceze, but he did not say that in the question. He does not appear to be using the **Ternary Operator** at all, as it's missing the colon (`:`) in his question. I'm pretty sure the `?` part is just punctuation.
Mark Tomlin
@Mark I know, I know. Half-humorous statements are difficult on a tech site... `<highlight>`:o)`</highlight>`
deceze
lol, sorry mate. It does not come over well without `<sarcasm>` tags.
Mark Tomlin
+1  A: 

-95 is the answer as if u will echo $b u will get output as "a" and if u echo $a u will get out but as "5"

hence in this sense when u $(echo $b) which same as $(a) hence u will get it as "5-100" which is "-95"

OM The Eternity
A: 

the answer is -95

$a - 100
lemon