Tricky PHP Interview Questions (Part 1)

Doron Mor
Doron Mor
Aug 31, 2018 · 3 min read

Hey everyone.

Today I’m going to present to you some interesting PHP questions that can easily fool with your mind, but once you get how the PHP compiler works it will become very clear.

This is a multiple part story, so stay tuned.
In this part we will introduce 3 questions with full explanations.
* Please note that the PHP version I’ll be working with is 7.1.9.


Question number #1

What is the output of the code below?

$a = 3;
$b = &$a;
$a = 12 + $b;
$b = $b * 2;
echo $a;

.

.

.

Answer:
30

Ok so what is happaning here?
On the first line $a = 3; we simpley set $a to be 3 as an integer.
On the second line $b = &$a; we set $b to become reference to $a , so whenever we change $a we actually change $b and vice versa.
On the third line $a = 12 + $b; we set $a to be 12 + $b , and don’t you forget that $b is same as $a so this line becomes $a = 15; .
On the fourth line $b = $b * 2; we set $b to be $b * 2 , and again don’t forget that $b is a reference to $a so this line becomes $a = 30; .
So this is why we print 30.


Question number #2

What is the output of the code below?

$a = [];
$a = $a ? true : false ? 'true' : 'false';
$b = $a ? 'false' : 'true' ? 'true' : 'false';
echo $b;

.

.

.

Answer:
true

Ok so what is happaning here?
On the first line $a = []; we simpley set$a to an empty array.
On the second line $a = $a ? true : false ? 'true' : 'false';
we set $a to be the result of a double ternary operator, the first part evaluates to false due to the fact that empty array will be false in boolean expression, then the second part evaluates to false as ternary will always do on false.
On the third line $b = $a ? 'false' : 'true' ? 'true' : 'false';
we set $b to be the result of a double ternary operator, the first part evaluates to false due to the fact that non empty string will always be true in boolean expression, then the second part evaluates to true as ternary will always do on true.
So this is why we print true.


Question number #3

What is the output of the code below?

$a = 0b11 + 11 + '11' + 011 + '011' + 0x11;
echo $a;

.

.

.

Answer:
62

Ok so what is happaning here?
Few things to know first:

  • 0b11 is 3 in binary.
  • 11 is decimal number.
  • '11' is decimal number (when handled as a number).
  • 011 is 9 in octal.
  • '011' is NOT octal! but rather decimal number (when handled as a number).
  • 0x11 is 17 in hexadecimal.

when we sum it all up 3 + 11 + 11 + 9 + 11 + 17 we get 62.
So this is why we print 62.


Thats all for this story,

See you next time :)

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade