0

So I know with JSLint syntax you always use ===. In PHP I've always done ==. I understand that in PHP == means 'loosely the same' and === means 'strictly the same'. I have two questions.

1) Is it best practice to use === in PHP? (I know I'll have to change some of my code.)

2) Do the == and === in Javascript represent the same differences as they do in PHP?

chrislondon
  • 12,487
  • 5
  • 26
  • 65
  • Possibly related: http://stackoverflow.com/questions/359494/javascript-vs-does-it-matter-which-equal-operator-i-use – Joe Malt Jul 04 '13 at 15:52
  • Thanks @yttriuszzerbus I tried searching SO for === but it didn't come up with any questions – chrislondon Jul 04 '13 at 15:54
  • Regarding (2): Yes, but conversion rules between data types are probably different. Using strict comparison in any language is good IMO. It's easier to prevent bugs. Use loose comparison only if you really want it. – Felix Kling Jul 04 '13 at 15:55

3 Answers3

5

In PHP == contains a whole new dimension of WTF compared to Javascript ==. For example, in PHP, == will actually parse strings for numbers and compare those, so for example, in PHP "000" == "0" is true. In Javascript that is false because they are obviously 2 different strings by any rational definition of string equality.

As for Javascript == in general, the rules for it are surprisingly simple if you read the actual rules for them in the specification (I still won't use it because the average joe obviously doens't read specs). In PHP I would always use === because there is no specification - just ad hoc examples of comparisons. I had to read about the string parsing in PHP source code for example.


Another really fun effect of the PHP == string parsing is that if the string cannot be parsed into machine integer, it will just be compared as string. So the same equality comparison can give different results depending on whether the PHP runs under 32-bit or 64-bit. Fun times.

Esailija
  • 138,174
  • 23
  • 272
  • 326
0

In PHP === you should use if you want to check also the type of value. If the type is not important, the good practise is to use just a ==.

Paweł Zegardło
  • 298
  • 3
  • 10
  • Where did you read it's a good practice to use `==` when type is not important ? Because I think it's the opposite, considering how `==` compares values – nice ass Nov 04 '13 at 00:18
-1

Yes == and === have the same meaning in javascript as they do in PHP.

It's not necessarily best practice to use === over == in PHP but you need to be mindful of when to use ===.

Example 1:

<?php
$str = 'abcde';
if (strstr($str, 'a') == false {
    // This line will get printed as strstr() will return the position of a
    // which is 0 and 0 == false but 0 !== false so === is needed
    print 'a is not in the string';
}
?>

Example 2:

<?php
$a = 1;
$b = '1';
$a == $b; //true
$a === $b //false
RMcLeod
  • 2,561
  • 1
  • 22
  • 38