PHP: Таблица сравнения типов в PHP - Manual

downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

List of Parser Tokens Unix-сокеты: UNIX и UDG

Last updated: Sat, 27 Jan 2007

view this page in

# Приложение 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 = "";` | строка | `TRUE` | `FALSE` | `TRUE` | `FALSE`
`$x = `NULL`` | NULL | `TRUE` | `TRUE` | `FALSE` | `FALSE`
`var $x;` | NULL | `TRUE` | `TRUE` | `FALSE` | `FALSE`
`$x` неопределена | NULL | `TRUE` | `TRUE` | `FALSE` | `FALSE`
`$x = array();` | массив | `TRUE` | `FALSE` | `TRUE` | `FALSE`
`$x = false;` | логическое | `TRUE` | `FALSE` | `TRUE` | `FALSE`
`$x = true;` | логическое | `FALSE` | `FALSE` | `TRUE` | `TRUE`
`$x = 1;` | целое | `FALSE` | `FALSE` | `TRUE` | `TRUE`
`$x = 42;` | целое | `FALSE` | `FALSE` | `TRUE` | `TRUE`
`$x = 0;` | целое | `TRUE` | `FALSE` | `TRUE` | `FALSE`
`$x = -1;` | целое | `FALSE` | `FALSE` | `TRUE` | `TRUE`
`$x = "1";` | строка | `FALSE` | `FALSE` | `TRUE` | `TRUE`
`$x = "0";` | строка | `TRUE` | `FALSE` | `TRUE` | `FALSE`
`$x = "-1";` | строка | `FALSE` | `FALSE` | `TRUE` | `TRUE`
`$x = "php";` | строка | `FALSE` | `FALSE` | `TRUE` | `TRUE`
`$x = "true";` | строка | `FALSE` | `FALSE` | `TRUE` | `TRUE`
`$x = "false";` | строка | `FALSE` | `FALSE` | `TRUE` | `TRUE`

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

| `TRUE` | `FALSE` | `1` | `0` | `-1` | `"1"` | `"0"` | `"-1"` | `NULL` | `array()` | `"php"`
--- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | ---
`TRUE` | `TRUE` | `FALSE` | `TRUE` | `FALSE` | `TRUE` | `TRUE` | `FALSE` | `TRUE` | `FALSE` | `FALSE` | `TRUE`
`FALSE` | `FALSE` | `TRUE` | `FALSE` | `TRUE` | `FALSE` | `FALSE` | `TRUE` | `FALSE` | `TRUE` | `TRUE` | `FALSE`
`1` | `TRUE` | `FALSE` | `TRUE` | `FALSE` | `FALSE` | `TRUE` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `FALSE`
`0` | `FALSE` | `TRUE` | `FALSE` | `TRUE` | `FALSE` | `FALSE` | `TRUE` | `FALSE` | `TRUE` | `FALSE` | `TRUE`
`-1` | `TRUE` | `FALSE` | `FALSE` | `FALSE` | `TRUE` | `FALSE` | `FALSE` | `TRUE` | `FALSE` | `FALSE` | `FALSE`
`"1"` | `TRUE` | `FALSE` | `TRUE` | `FALSE` | `FALSE` | `TRUE` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `FALSE`
`"0"` | `FALSE` | `TRUE` | `FALSE` | `TRUE` | `FALSE` | `FALSE` | `TRUE` | `FALSE` | `FALSE` | `FALSE` | `FALSE`
`"-1"` | `TRUE` | `FALSE` | `FALSE` | `FALSE` | `TRUE` | `FALSE` | `FALSE` | `TRUE` | `FALSE` | `FALSE` | `FALSE`
`NULL` | `FALSE` | `TRUE` | `FALSE` | `TRUE` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `TRUE` | `TRUE` | `FALSE`
`array()` | `FALSE` | `TRUE` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `TRUE` | `FALSE`
`"php"` | `TRUE` | `FALSE` | `FALSE` | `TRUE` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `TRUE`

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

| `TRUE` | `FALSE` | `1` | `0` | `-1` | `"1"` | `"0"` | `"-1"` | `NULL` | `array()` | `"php"`
--- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | ---
`TRUE` | `TRUE` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `FALSE`
`FALSE` | `FALSE` | `TRUE` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `FALSE`
`1` | `FALSE` | `FALSE` | `TRUE` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `FALSE`
`0` | `FALSE` | `FALSE` | `FALSE` | `TRUE` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `FALSE`
`-1` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `TRUE` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `FALSE`
`"1"` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `TRUE` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `FALSE`
`"0"` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `TRUE` | `FALSE` | `FALSE` | `FALSE` | `FALSE`
`"-1"` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `TRUE` | `FALSE` | `FALSE` | `FALSE`
`NULL` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `TRUE` | `FALSE` | `FALSE`
`array()` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `TRUE` | `FALSE`
`"php"` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `FALSE` | `TRUE`

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

add a note User Contributed Notes
Таблица сравнения типов в PHP
omit
23-Aug-2006 11:32
`the manual said "HTML Forms do not pass integers, floats, or booleans; they pass strings"
while this is true, php will sometimes change the type to either type array, or possibly type integer(no, not a numeric string) if it was used as an array key. php seems to do this when it parses the request data into the predefined variable arrays.
example:
<input type="text" name="foo[5]">
<input type="text" name="foo[7]">
now obviously the browser will send those names as a string. but php will change thier type.
<?php
// $_POST['foo'] is an array
var_dump($_POST['foo']);
foreach ($_POST['foo'] as $key => $val) {
// the keys 5 and 7 will be type integer
var_dump($key);
}
?>
because of this, its also a good idea to check the types of your variables.`
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.`
add a note
List of Parser Tokens Unix-сокеты: UNIX и UDG

Last updated: Sat, 27 Jan 2007
show source | credits | stats | sitemap | contact | advertising | mirror sites
Copyright © 2001-2007 The PHP Group
All rights reserved.
This mirror generously provided by: Yahoo! Inc.
Last updated: Sat Mar 10 09:32:46 2007 PST