ЛогичСскиС значСния

ЛогичСский Ρ‚ΠΈΠΏ (bool) ΠΏΡ€ΠΈΠ½ΠΈΠΌΠ°Π΅Ρ‚ Ρ‚ΠΎΠ»ΡŒΠΊΠΎ Π΄Π²Π° значСния, ΠΊΠΎΡ‚ΠΎΡ€Ρ‹Π΅ Π²Ρ‹Ρ€Π°ΠΆΠ°ΡŽΡ‚ ΠΈΡΡ‚ΠΈΠ½Π½ΠΎΡΡ‚ΡŒ: true ΠΈΠ»ΠΈ false.

Бинтаксис

ЛогичСскиС Π»ΠΈΡ‚Π΅Ρ€Π°Π»Ρ‹ β€” значСния с Ρ‚ΠΈΠΏΠΎΠΌ bool β€” ΡƒΠΊΠ°Π·Ρ‹Π²Π°ΡŽΡ‚ константами true ΠΈΠ»ΠΈ false. ОбС константы рСгистронСзависимы.

<?php

$foo
= True; // ΠŸΡ€ΠΈΡΠ²ΠΎΠΈΡ‚ΡŒ ΠΏΠ΅Ρ€Π΅ΠΌΠ΅Π½Π½ΠΎΠΉ $foo Π·Π½Π°Ρ‡Π΅Π½ΠΈΠ΅ TRUE

var_dump($foo); // bool(true)

ЛогичСскиС условия часто ΠΏΡ€ΠΎΠ²Π΅Ρ€ΡΡŽΡ‚ Π² ΡƒΠΏΡ€Π°Π²Π»ΡΡŽΡ‰ΠΈΡ… конструкциях. Π’Π½ΡƒΡ‚Ρ€ΠΈ конструкций Π²Ρ‹ΠΏΠΎΠ»Π½ΡΡŽΡ‚ ΠΎΠΏΠ΅Ρ€Π°Ρ†ΠΈΠΈ, Ρ€Π΅Π·ΡƒΠ»ΡŒΡ‚Π°Ρ‚ΠΎΠΌ ΠΊΠΎΡ‚ΠΎΡ€Ρ‹Ρ… становятся значСния с Ρ‚ΠΈΠΏΠΎΠΌ bool.

<?php

$action
= "show_version";
$show_separators = true;

// ΠžΠΏΠ΅Ρ€Π°Ρ‚ΠΎΡ€ == ΠΏΡ€ΠΎΠ²Π΅Ρ€ΠΈΡ‚
// равСнство ΠΈ Π²Ρ‹Ρ€Π°ΠΆΠ΅Π½ΠΈΠ΅ вычислится ΠΊΠ°ΠΊ логичСскоС Π·Π½Π°Ρ‡Π΅Π½ΠΈΠ΅
if ($action == "show_version") {
echo
"ВСрсия 1.23";
}

// Π‘Ρ€Π°Π²Π½Π΅Π½ΠΈΠ΅ логичСской ΠΏΠ΅Ρ€Π΅ΠΌΠ΅Π½Π½ΠΎΠΉ со Π·Π½Π°Ρ‡Π΅Π½ΠΈΠ΅ΠΌ true ΠΈΠ·Π±Ρ‹Ρ‚ΠΎΡ‡Π½ΠΎ,...
if ($show_separators == TRUE) {
echo
"<hr>\n";
}

// ...ΠΏΠΎΡΠΊΠΎΠ»ΡŒΠΊΡƒ ΠΏΡ€ΠΎΠ²Π΅Ρ€ΠΊΠ° Π±Π΅Π· сравнСния Π΄Π°Ρ‘Ρ‚ Π°Π½Π°Π»ΠΎΠ³ΠΈΡ‡Π½Ρ‹ΠΉ Ρ€Π΅Π·ΡƒΠ»ΡŒΡ‚Π°Ρ‚:
if ($show_separators) {
echo
"<hr>\n";
}

ΠŸΡ€Π΅ΠΎΠ±Ρ€Π°Π·ΠΎΠ²Π°Π½ΠΈΠ΅ Π² логичСский Ρ‚ΠΈΠΏ

ΠžΠΏΠ΅Ρ€Π°Ρ‚ΠΎΡ€ (bool) явно ΠΏΡ€ΠΈΠ²ΠΎΠ΄ΠΈΡ‚ Π·Π½Π°Ρ‡Π΅Π½ΠΈΠ΅ ΠΊ Ρ‚ΠΈΠΏΡƒ bool. Π’ большСй части сцСнариСв Ρ€ΡƒΡ‡Π½ΠΎΠ΅ ΠΏΡ€Π΅ΠΎΠ±Ρ€Π°Π·ΠΎΠ²Π°Π½ΠΈΠ΅ Ρ‚ΠΈΠΏΠ° Π½Π΅ потрСбуСтся, ΠΏΠΎΡΠΊΠΎΠ»ΡŒΠΊΡƒ Π² логичСском контСкстС Π·Π½Π°Ρ‡Π΅Π½ΠΈΠ΅ автоматичСски интСрпрСтируСтся ΠΊΠ°ΠΊ Π·Π½Π°Ρ‡Π΅Π½ΠΈΠ΅ с Ρ‚ΠΈΠΏΠΎΠΌ bool. Π”ΠΎΠΏΠΎΠ»Π½ΠΈΡ‚Π΅Π»ΡŒΠ½ΡƒΡŽ ΠΈΠ½Ρ„ΠΎΡ€ΠΌΠ°Ρ†ΠΈΡŽ ΠΎ ΠΏΡ€ΠΈΠ²Π΅Π΄Π΅Π½ΠΈΠΈ Ρ‚ΠΈΠΏΠΎΠ² Π΄Π°Ρ‘Ρ‚ Ρ€Π°Π·Π΄Π΅Π» Β«Π–ΠΎΠ½Π³Π»ΠΈΡ€ΠΎΠ²Π°Π½ΠΈΠ΅ Ρ‚ΠΈΠΏΠ°ΠΌΠΈΒ».

ΠŸΡ€ΠΈ ΠΏΡ€Π΅ΠΎΠ±Ρ€Π°Π·ΠΎΠ²Π°Π½ΠΈΠΈ Π² Ρ‚ΠΈΠΏ bool ΡΠ»Π΅Π΄ΡƒΡŽΡ‰ΠΈΠ΅ значСния ΠΈΠ½Ρ‚Π΅Ρ€ΠΏΡ€Π΅Ρ‚ΠΈΡ€ΡƒΡŽΡ‚ΡΡ ΠΊΠ°ΠΊ false:

  • само Π·Π½Π°Ρ‡Π΅Π½ΠΈΠ΅ boolean false
  • integer 0 (ноль)
  • float 0.0 (ноль) ΠΈ -0.0 (минус ноль)
  • пустая строка "" ΠΈ строка "0"
  • массив Π±Π΅Π· элСмСнтов
  • особый Ρ‚ΠΈΠΏ NULL (Π²ΠΊΠ»ΡŽΡ‡Π°Ρ нСустановлСнныС ΠΏΠ΅Ρ€Π΅ΠΌΠ΅Π½Π½Ρ‹Π΅)
  • Π²Π½ΡƒΡ‚Ρ€Π΅Π½Π½ΠΈΠ΅ ΠΎΠ±ΡŠΠ΅ΠΊΡ‚Ρ‹, ΠΊΠΎΡ‚ΠΎΡ€Ρ‹Π΅ ΠΏΠ΅Ρ€Π΅Π³Ρ€ΡƒΠΆΠ°ΡŽΡ‚ своё ΠΏΠΎΠ²Π΅Π΄Π΅Π½ΠΈΠ΅ привСдСния ΠΊ логичСскому Ρ‚ΠΈΠΏΡƒ. НапримСр: ΠΎΠ±ΡŠΠ΅ΠΊΡ‚Ρ‹ GMP, ΠΊΠΎΡ‚ΠΎΡ€Ρ‹Π΅ ΠΏΡ€Π΅Π΄ΡΡ‚Π°Π²Π»ΡΡŽΡ‚ Π·Π½Π°Ρ‡Π΅Π½ΠΈΠ΅ 0.

ВсС ΠΎΡΡ‚Π°Π»ΡŒΠ½Ρ‹Π΅ значСния ΡΡ‡ΠΈΡ‚Π°ΡŽΡ‚ΡΡ true (Π²ΠΊΠ»ΡŽΡ‡Π°Ρ resource ΠΈ NAN).

Π’Π½ΠΈΠΌΠ°Π½ΠΈΠ΅

Число -1 PHP ΠΎΡ†Π΅Π½ΠΈΠ²Π°Π΅Ρ‚ ΠΊΠ°ΠΊ логичСскоС Π·Π½Π°Ρ‡Π΅Π½ΠΈΠ΅ true, ΠΊΠ°ΠΊ ΠΈ любоС Π΄Ρ€ΡƒΠ³ΠΎΠ΅ Π½Π΅Π½ΡƒΠ»Π΅Π²ΠΎΠ΅ β€” ΠΎΡ‚Ρ€ΠΈΡ†Π°Ρ‚Π΅Π»ΡŒΠ½ΠΎΠ΅ ΠΈΠ»ΠΈ ΠΏΠΎΠ»ΠΎΠΆΠΈΡ‚Π΅Π»ΡŒΠ½ΠΎΠ΅ β€” число!

ΠŸΡ€ΠΈΠΌΠ΅Ρ€ #1 ΠŸΡ€ΠΈΠ²Π΅Π΄Π΅Π½ΠΈΠ΅ ΠΊ логичСскому Ρ‚ΠΈΠΏΡƒ

<?php

var_dump
((bool) ""); // bool(false)
var_dump((bool) "0"); // bool(false)
var_dump((bool) 1); // bool(true)
var_dump((bool) -2); // bool(true)
var_dump((bool) "foo"); // bool(true)
var_dump((bool) 2.3e5); // bool(true)
var_dump((bool) array(12)); // bool(true)
var_dump((bool) array()); // bool(false)
var_dump((bool) "false"); // bool(true)
οΌ‹Π”ΠΎΠ±Π°Π²ΠΈΡ‚ΡŒ

ΠŸΡ€ΠΈΠΌΠ΅Ρ‡Π°Π½ΠΈΡ ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Π΅ΠΉ 12 notes

up
1005
Fred Koschara ΒΆ
13 years ago
Ah, yes, booleans - bit values that are either set (TRUE) or not set (FALSE).  Now that we have 64 bit compilers using an int variable for booleans, there is *one* value which is FALSE (zero) and 2**64-1 values that are TRUE (everything else).  It appears there's a lot more truth in this universe, but false can trump anything that's true...

PHP's handling of strings as booleans is *almost* correct - an empty string is FALSE, and a non-empty string is TRUE - with one exception:  A string containing a single zero is considered FALSE.  Why?  If *any* non-empty strings are going to be considered FALSE, why *only* a single zero?  Why not "FALSE" (preferably case insensitive), or "0.0" (with how many decimal places), or "NO" (again, case insensitive), or ... ?

The *correct* design would have been that *any* non-empty string is TRUE - period, end of story.  Instead, there's another GOTCHA for the less-than-completely-experienced programmer to watch out for, and fixing the language's design error at this late date would undoubtedly break so many things that the correction is completely out of the question.

Speaking of GOTCHAs, consider this code sequence:
<?php
$x=TRUE;
$y=FALSE;
$z=$y OR $x;
?>

Is $z TRUE or FALSE?

In this case, $z will be FALSE because the above code is equivalent to <?php ($z=$y) OR $x ?> rather than <?php $z=($y OR $x) ?> as might be expected - because the OR operator has lower precedence than assignment operators.

On the other hand, after this code sequence:
<?php
$x=TRUE;
$y=FALSE;
$z=$y || $x;
?>

$z will be TRUE, as expected, because the || operator has higher precedence than assignment:  The code is equivalent to $z=($y OR $x).

This is why you should NEVER use the OR operator without explicit parentheses around the expression where it is being used.
up
180
Mark Simon ΒΆ
9 years ago
Note for JavaScript developers:

In PHP, an empty array evaluates to false, while in JavaScript an empty array evaluates to true.

In PHP, you can test an empty array as <?php if(!$stuff) …; ?> which won’t work in JavaScript where you need to test the array length.

This is because in JavaScript, an array is an object, and, while it may not have any elements, it is still regarded as something.

Just a trap for young players who routinely work in both langauges.
up
101
goran77 at fastmail dot fm ΒΆ
9 years ago
Just something that will probably save time for many new developers: beware of interpreting FALSE and TRUE as integers. 
For example, a small function for deleting elements of an array may give unexpected results if you are not fully aware of what happens: 

<?php

function remove_element($element, $array)
{
   //array_search returns index of element, and FALSE if nothing is found
   $index = array_search($element, $array);
   unset ($array[$index]);
   return $array; 
}

// this will remove element 'A'
$array = ['A', 'B', 'C'];
$array = remove_element('A', $array);

//but any non-existent element will also remove 'A'!
$array = ['A', 'B', 'C'];
$array = remove_element('X', $array);
?>

The problem here is, although array_search returns boolean false when it doesn't find specific element, it is interpreted as zero when used as array index.

So you have to explicitly check for FALSE, otherwise you'll probably loose some elements:

<?php
//correct
function remove_element($element, $array)
{
   $index = array_search($element, $array);
   if ($index !== FALSE) 
   {
       unset ($array[$index]);
   }
   return $array; 
}
up
58
terminatorul at gmail dot com ΒΆ
19 years ago
Beware that "0.00" converts to boolean TRUE !

You may get such a string from your database, if you have columns of type DECIMAL or CURRENCY. In such cases you have to explicitly check if the value is != 0 or to explicitly convert the value to int also, not only to boolean.
up
26
Mark Simon ΒΆ
9 years ago
Note on the OR operator.

A previous comment notes the trap you can fall into with this operator. This is about its usefulness.

Both OR and || are short-circuited operators, which means they will stop evaluating once they reach a TRUE value. By design, OR is evaluated after assignment (while || is evaluated before assignment).

This has the benefit of allowing some simple constructions such as:

<?php
    $stuff=getStuff() or die('oops');
    $thing=something() or $thing=whatever();
?>

The first example, often seen in PERL, could have been written as <?php if(!$stuff=getStuff()) die('oops'); ?> but reads a little more naturally. I have often used it in situations where null or false indicate failure.

The second allows for an alternative value if a falsy one is regarded as insufficient. The following example

<?php
    $page=@$_GET['page'] or $page=@$_COOKIE['page'] or $page=1;
?>

is a simple way sequencing alternative values. (Note the usual warnings about using the @ operator or accepting unfiltered input …)

All this presupposes that 0 is also an unacceptable value in the situation.
up
10
asma dot gi dot 14 at gmail dot com ΒΆ
5 years ago
when using echo false; or print false; the display will be empty but when using echo 0; or print 0; the display will be 0.
up
47
Steve ΒΆ
18 years ago
PHP does not break any rules with the values of true and false.  The value false is not a constant for the number 0, it is a boolean value that indicates false.  The value true is also not a constant for 1, it is a special boolean value that indicates true.  It just happens to cast to integer 1 when you print it or use it in an expression, but it's not the same as a constant for the integer value 1 and you shouldn't use it as one.  Notice what it says at the top of the page:

A boolean expresses a truth value.

It does not say "a boolean expresses a 0 or 1".

It's true that symbolic constants are specifically designed to always and only reference their constant value.  But booleans are not symbolic constants, they are values.  If you're trying to add 2 boolean values you might have other problems in your application.
up
38
Wackzingo ΒΆ
18 years ago
It is correct that TRUE or FALSE should not be used as constants for the numbers 0 and 1. But there may be times when it might be helpful to see the value of the Boolean as a 1 or 0. Here's how to do it.

<?php
$var1 = TRUE;
$var2 = FALSE;

echo $var1; // Will display the number 1

echo $var2; //Will display nothing

/* To get it to display the number 0 for
a false value you have to typecast it: */

echo (int)$var2; //This will display the number 0 for false.
?>
up
7
asma dot gi dot 14 at gmail dot com ΒΆ
5 years ago
Please keep in mind that the result of  0 == 'whatever'  is true in PHP Version 7 and false in PHP version 8.
up
28
artktec at gmail dot com ΒΆ
18 years ago
Note you can also use the '!' to convert a number to a boolean, as if it was an explicit (bool) cast then NOT.

So you can do something like:

<?php
$t = !0; // This will === true;
$f = !1; // This will === false;
?>

And non-integers are casted as if to bool, then NOT.

Example:

<?php
$a = !array();      // This will === true;
$a = !array('a');   // This will === false;
$s = !"";           // This will === true;
$s = !"hello";      // This will === false;
?>

To cast as if using a (bool) you can NOT the NOT with "!!" (double '!'), then you are casting to the correct (bool).

Example:

<?php
$a = !!array();   // This will === false; (as expected)
/* 
This can be a substitute for count($array) > 0 or !(empty($array)) to check to see if an array is empty or not  (you would use: !!$array).
*/

$status = (!!$array ? 'complete' : 'incomplete');

$s = !!"testing"; // This will === true; (as expected)
/* 
Note: normal casting rules apply so a !!"0" would evaluate to an === false
*/
?>
up
0
Anonymous ΒΆ
2 years ago
Note the imperfectness of php and booleans when dealing with SQL strings. A 'boolean' included in a string to send to MySQL for example, evaluates to a n empty string with the result that:

$TF  = false;
$SQL = "INSERT INTO ... (...., booleanTF) VALUES (...., $TF)" 

will generate a mysql error "You have an error ... near '(....,)"
up
2
marklgr ΒΆ
10 years ago
For those wondering why the string "0" is falsy, consider that a good deal of input data is actually string-typed, even when it is semantically numeral.

PHP often tries to autoconvert these strings to numeral, as the programmer certainly intended (try 'echo "2"+3'). Consequently, PHP designers decided to treat 0 and "0" similarly, ie. falsy, for consistency and to avoid bugs where the programmer believes he got a true numeral that would happen to be truthy when zero.