1

I know, or better I agree, with the irrelevant importance of speed performance in php, at least in the majority of common cases.

But I'm wondering "if" and "why" inside an if construct the expression

if("hello" === $var)

could have better performance than

if($var === "hello")

May be because in the first example there's no internal type conversion of the variable?

I'm quite sure I've read something about it but I can't find it anymore.

ilpaijin
  • 3,645
  • 2
  • 23
  • 26

2 Answers2

4

That is called Yoda notation.

As Sanjog mentioned, it is used to avoid making the mistake of making an assignment instead of verifying an equality.

The main problem though is that this method is not a great practice in terms of making nice code.

The book "The Art of Readable Code" has an interesting comment on that:

In some languages (including C and C++, but not Java), it’s legal to put an assignment inside an if condition:

if (obj = NULL) ...

Most likely this is a bug, and the programmer actually meant:

if (obj == NULL) ...

To prevent bugs like this, many programmers switch the order of arguments:

if (NULL == obj) ...

This way, if == is accidentally written as =, the expression if (NULL = obj) won’t even compile. Unfortunately, switching the order makes the code a bit unnatural to read. (As Yoda would say, “Not if anything to say about it I have.”) Thankfully, modern compilers warn against code like if (obj = NULL), so “Yoda Notation” is becoming a thing of the past.


Unfortunately for you, assignments inside if's are not illegal in PHP.

Gumbo
  • 643,351
  • 109
  • 780
  • 844
DanielX2010
  • 1,897
  • 1
  • 24
  • 26
  • So it has nothing to do with performance. I found sometimes useful to make an assignment inside an if `if (evaluate to true or false) then`; So perhaps am I wrong? – ilpaijin Nov 16 '13 at 10:05
  • @ilpaijin Yes, it has no influence on performance. It is not wrong to do an assignment inside an if, if you do it on purpose. What Yoda notation tries to prevent is doing it accidentally whaen you actually want a `==` – DanielX2010 Nov 16 '13 at 21:15
2

The difference is given below

if ($foo == 3) bar();

In this case If I forgot a = it will not show me the error

if (3 == $foo) bar();

this way, if you forget a =, it will become

if (3 = $foo) bar();

and PHP will report an error.