Fundamental php type comparison philosophy

So, here is this page on the php site, which shows the result of comparing different values:

http://php.net/manual/en/types.comparisons.php

This is a useful link, but I would prefer not to visit this page every time I want to make sure that I am doing type comparisons correctly. So my question is:

Is there any basic philosophy / logic of type comparison logic in PHP?

For example, I see that for free comparison:

  • 1, -1, "1" and "-1" can be interpreted as TRUE, and 0 and "0" can be considered as FALSE;
  • Comparison of the string value of a number with the number itself with the TRUE output;

but since then he gets a little hairy trying to set a pattern.

+5
source share
7 answers

For casting directly to a logical, this works.

  • The entire string with a length> 0 is correct.
  • All values โ€‹โ€‹other than 0 are true.
  • All non-empty arrays are true.
  • All objects are correct.

Then these rules for comparing variables of the same type:

  • Objects are equivalent if their properties are equal.
  • Arrays are equivalent if their keys and elements are equal.
  • Strings are equivalent if they produce the same output
  • Numbers are equivalent if they are mathematically equivalent
  • Booleans are equivalent if they have the same value.

For a variable of different types, the type that is higher in the above list is converted to one that is lower than the comparison.

Operators

=== !== , , ===, .

- , ===, , .

$a = array("a"=>1, "b"=>2);
$b = array("b"=>2, "a"=>1);

$a == $b; // true
$a === $b; // false

empty() !(bool)$var

  • Array
  • __toString .
  • , , , (UPDATE), , ArrayAccess)
+6

=== : , TRUE === TRUE, "1" === "1", "1" !== 1 ..

== , , , . , , . , , :

PHP equality graph

: A == B TRUE , A B , . , array() == NULL TRUE, array() NULL , array() == 0 - FALSE, , .

, , ( ) .

, (, "1" == "1" ..), .

, , "php" == 0 TRUE ( , 0): PHP "php" , , 0 TRUE.

: ! , , True , False - , PHP: D

+4

-, true. , 1, 1.123, array("value") .. true.

(.. -), false. , 0, 0.0, array() ..

PHP. . . Perl, C Javascript, .

+2

, .

. .

( ) php : , , , .

0 "0", , false ( ). : , false, , false, 0, 0.

null array() . , (), , true. , , is_null, false. , , array(), array(), '', null. , is_null() == null === null , , . Null is_array(), . is_array(), . , , null array().

+2

, .

  • "" (null, false, 0, '0') false
  • , ( , , )
  • , , array_key_exists strict
  • return ($something); $something ,
+1

, C: , , .

.

- '0', ( ) , . array(0) .

(=== !==) . , , , .

+1

:

  • PHP is designed as a web programming language, and all page input is line-based [humanoid perception] [This, by the way, is also true for JavaScript]
  • Therefore, all strings that look like numbers (is_numeric () function) pre-behave like numbers [comparison, casting].
  • This explains why extreme cases, such as "0", are first implicitly considered cast from (int) 0, but only to false.
0
source

All Articles