Приложение P. Таблица сравнения типов в PHP

Следующие таблицы демонстрируют работу PHP с типами переменных и операторами сравнения, как в случае свободного, так и в случае строгого сравнения. Также эта информация относится к разделу документации по приведению типов. Вдохновением на создание этого раздела мы обязаны различным комментариям пользователей и работе над BlueShoes.

До осмотра таблиц, важно знать и понимать типы переменных и их значения. К примеру, "42" -- строка, в то время как 42 -- целое. FALSE -- логическое, а "false" -- строка.

Замечание: HTML-формы не передают тип переменной: они всегда передают строки. Для проверки является ли строка числом, используйте функцию is_numeric().

Замечание: Использование if ($x) пока $x не определена сгенерирует ошибку E_NOTICE. Вместо этого используйте функцию empty() или isset() и/или инициализируйте переменную.

Таблица P-1. Сравнение типов $x и результатов функций PHP, связанных с типами

Выражениеgettype()empty()is_null()isset()логическое : if($x)
$x = "";строкаTRUEFALSETRUEFALSE
$x = NULLNULLTRUETRUEFALSEFALSE
var $x;NULLTRUETRUEFALSEFALSE
$x неопределенаNULLTRUETRUEFALSEFALSE
$x = array();массивTRUEFALSETRUEFALSE
$x = false;логическоеTRUEFALSETRUEFALSE
$x = true;логическоеFALSEFALSETRUETRUE
$x = 1;целоеFALSEFALSETRUETRUE
$x = 42;целоеFALSEFALSETRUETRUE
$x = 0;целоеTRUEFALSETRUEFALSE
$x = -1;целоеFALSEFALSETRUETRUE
$x = "1";строкаFALSEFALSETRUETRUE
$x = "0";строкаTRUEFALSETRUEFALSE
$x = "-1";строкаFALSEFALSETRUETRUE
$x = "php";строкаFALSEFALSETRUETRUE
$x = "true";строкаFALSEFALSETRUETRUE
$x = "false";строкаFALSEFALSETRUETRUE

Таблица P-2. Гибкое сравнение с помощью ==

 TRUEFALSE10-1"1""0""-1"NULLarray()"php"
TRUETRUEFALSETRUEFALSETRUETRUEFALSETRUEFALSEFALSETRUE
FALSEFALSETRUEFALSETRUEFALSEFALSETRUEFALSETRUETRUEFALSE
1TRUEFALSETRUEFALSEFALSETRUEFALSEFALSEFALSEFALSEFALSE
0FALSETRUEFALSETRUEFALSEFALSETRUEFALSETRUEFALSETRUE
-1TRUEFALSEFALSEFALSETRUEFALSEFALSETRUEFALSEFALSEFALSE
"1"TRUEFALSETRUEFALSEFALSETRUEFALSEFALSEFALSEFALSEFALSE
"0"FALSETRUEFALSETRUEFALSEFALSETRUEFALSEFALSEFALSEFALSE
"-1"TRUEFALSEFALSEFALSETRUEFALSEFALSETRUEFALSEFALSEFALSE
NULLFALSETRUEFALSETRUEFALSEFALSEFALSEFALSETRUETRUEFALSE
array()FALSETRUEFALSEFALSEFALSEFALSEFALSEFALSEFALSETRUEFALSE
"php"TRUEFALSEFALSETRUEFALSEFALSEFALSEFALSEFALSEFALSETRUE

Таблица P-3. Жёсткое сравнение с помощью ===

 TRUEFALSE10-1"1""0""-1"NULLarray()"php"
TRUETRUEFALSEFALSEFALSEFALSEFALSEFALSEFALSEFALSEFALSEFALSE
FALSEFALSETRUEFALSEFALSEFALSEFALSEFALSEFALSEFALSEFALSEFALSE
1FALSEFALSETRUEFALSEFALSEFALSEFALSEFALSEFALSEFALSEFALSE
0FALSEFALSEFALSETRUEFALSEFALSEFALSEFALSEFALSEFALSEFALSE
-1FALSEFALSEFALSEFALSETRUEFALSEFALSEFALSEFALSEFALSEFALSE
"1"FALSEFALSEFALSEFALSEFALSETRUEFALSEFALSEFALSEFALSEFALSE
"0"FALSEFALSEFALSEFALSEFALSEFALSETRUEFALSEFALSEFALSEFALSE
"-1"FALSEFALSEFALSEFALSEFALSEFALSEFALSETRUEFALSEFALSEFALSE
NULLFALSEFALSEFALSEFALSEFALSEFALSEFALSEFALSETRUEFALSEFALSE
array()FALSEFALSEFALSEFALSEFALSEFALSEFALSEFALSEFALSETRUEFALSE
"php"FALSEFALSEFALSEFALSEFALSEFALSEFALSEFALSEFALSEFALSETRUE

Заметка о PHP 3.0: Строка "0" считалась не пустой, в PHP4 ситуация изменилась: строка трактуется как пустая.



Таблица сравнения типов в PHP
Jan
29-Dec-2005 11:23
Note that php comparison is not transitive:

"php" == 0 => true
0 == null => true
null == "php" => false
php [at] barryhunter [.] co [.] uk
07-Sep-2005 12:44
In case it helps someone, here's a table to compare different Variable tests (created before I found this page!)

http://www.deformedweb.co.uk/php_variable_tests.php
jerryschwartz at comfortable dot com
26-Jul-2005 01:04
In some languages, a boolean is promoted to an integer (with a value of 1 or -1, typically) if used in an expression with an integer. I found that PHP has it both ways:

If you add a boolean with a value of true to an integer with a value of 3, the result will be 4 (because the boolean is cast as an integer).

On the other hand, if you test a boolean with a value of true for equality with an integer with a value of three, the result will be true (because the integer is cast as a boolean).

Surprisingly, at first glance, if you use either < or > as the comparison operator the result is always false (again, because the integer as cast as a boolean, and true is neither greater nor less than true).
tom
17-Jun-2005 02:27
<?php
if (strlen($_POST['var']) > 0) {
  
// form value is ok
}
?>

When working with HTML forms this a good way to:

(A) let "0" post values through like select or radio values that correspond to array keys or checkbox booleans that would return FALSE with empty(), and;
(B) screen out $x = "" values, that would return TRUE with isset()!

Because HTML forms post values as strings, this is a good way to test variables!

[[Editor Note: This will create a PHP Error of level E_NOTICE if the checked variable (in this case $_POST['var']) is undefined. It may be used after (in conjuection with) isset() to prevent this.]]
aidan at php dot net
24-Jan-2005 07:00
The way PHP handles comparisons when multiple types are concerned is quite confusing.

For example:
"php" == 0

This is true, because the string is casted interally to an integer. Any string (that does not start with a number), when casted to an integer, will be 0.

<Unix-сокеты: UNIX и UDGList of Parser Tokens>
 Last updated: Tue, 15 Nov 2005