Булев

Это простейший тип. Он выражает истинность значения - это может быть либо TRUE, либо FALSE.

Замечание: Булев тип был введен в PHP 4.

Синтаксис

Чтобы определить булев тип, используйте ключевое слово TRUE или FALSE. Оба регистро-независимы.

<?php
$foo
= True; // присвоить $foo значение TRUE
?>

Обычно вы используете некий оператор, который возвращает логическое выражение, а затем предает его управляющей конструкции.

<?php
// == это оператор, который проверяет
// эквивалентность и возвращает булево значение
if ($action == "показать_версию") {
   echo
"Версия 1.23";
}

// это не обязательно...
if ($show_separators == TRUE) {
   echo
"<hr>\n";
}

// ...потому что вы можете просто написать
if ($show_separators) {
   echo
"<hr>\n";
}
?>

Преобразование в булев тип

Для несомненного преобразования значения в булев тип используйте приведение типа (bool) или (boolean). Однако в большинстве случаев вам нет необходимости использовать приведение типа, поскольку значение будет автоматически преобразовано, если оператор, функция или управляющая конструкция требует булев аргумент.

Смотрите также Манипуляции с типами.

При преобразовании в логический тип, следующие значения рассматриваются как FALSE:

Все остальные значения рассматриваются как TRUE (включая любой ресурс).

Внимание

-1 считается TRUE, как и любое ненулевое (отрицательное или положительное) число!

<?php
var_dump
((bool) "");        // 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)
?>



Булев
jasper at jtey dot com
07-Jun-2006 02:16
A correction to my previous note below, with regards to the following code snippet:
<?php
// lower case vowel check (incorrect)
$c = "u";
$isVowel = $c == "a"||"e"||"i"||"o"||"u";
?>

The portion containing '$c == "a"||"e"||"i"||"o"||"u"' should be '$c == "a"|| $c == "e"|| $c == "i"|| $c == "o"|| $c == "u"' instead.  The correct code is therefore:

<?php
// lower case vowel check (corrected)
$c = "u";
$isVowel = $c == "a"|| $c == "e"|| $c == "i"|| $c == "o"|| $c == "u";
?>
jasper at jtey dot com
05-Jun-2006 12:51
The following expressions are equivalent:
<?php
// setting true
$flag = true;
$flag = True;
$flag = TRUE;
$flag = 1==1;

// setting false
$flag = false;
$flag = False;
$flag = FALSE;
$flag = 1==2;
?>

The moral of the story is that boolean operators return a boolean value, i.e., "1==1" returns a boolean value of true.  Someone who is not aware of this may write a block of code such as:
<?php
// even number?
$num = 10;
if(
$num % 2 == 0){
 
$isEven = true;
}
else{
 
$isEven = false;
}
?>

when all that is needed is:
<?php
$num
= 10;
$isEven = $num % 2 == 0;
?>

Other examples, for illustrative purposes:
<?php
// two numbers
$a = 2;
$b = 3;
$aBiggerThanB = 2 > 3; // $aBiggerThanB is set to false

// lower case vowel check
$c = "u";
$isVowel = $c == "a"||"e"||"i"||"o"||"u";
?>
alex dot baldacchino at email dot it
16-May-2006 09:48
About bnab at southphlattewebdesign dot com concern, I think that's globally a casting and backward compatibility matter: as this manual states, a boolean TRUE is converted to string "1" and this is meaningful being the number 1 a - let's say - "historical" true value, while a FALSE value is converted to an empty string for some reason (I guess that may be for concatenation reason or because of an internal representation of strings with the empty string as the first/main false value and the non empty "0" string being a sort of legacy/completness secondary false value).

This is the echo behaviour with boolean types, but let's note that boolean type have been introduced in php 4, while the preg_match function was introduced previously, in php 3.0.9, so it's returned type is integer and possible results are 0 for false and 1 for true (being this a "historical", or if preferred "(ANSI) C-like" convention), so in this case the echo function is not yet converting a boolean value to a string, but a number to a string, and number convertion rules applies. In order to preserve compatibility with such a convention, a numerical value of 0 is interpreted as a boolean false in a, let's say, boolean context, as well as the string "0", so to have a correct 0 (number) -> "0" (string) -> false (boolean) -> 0 (number, again) conversion.
bnab at southphlattewebdesign dot com
10-May-2006 04:05
Assignment of a boolean value:

I beat my head on this one: Depending upon how the boolean value is assigned, it determines the actual boolean value on a FALSE value - integer, empty string etc...

Take the following example:
<?php
$x
;
$i = true;
echo
$i.' I should be true or 1<br><br>'; //value = 1
$i = false;
echo
$i.' I should be false or 0<br><br>'; //value = ''
$i = isset($x);
echo
$i.' I should be false, as X has no value<br><br>'; //value = ''
$x = 'a string';
$i = preg_match('/str/',$x);
echo
$i.' I should be true on match<br><br>'; //value = 1
$i = preg_match('/trinsg/', $x);
echo
$i.' I should be false on no match'; //value = 0
?>

The preg_match is false on the second time around, and thus is now assigned the boolean false value of 0.  While in trying to create a boolean literal with value false, it gets assigned as an empty string false value.  Further, I run the isset check and it assigns the empty string, while preg_match assigns the 0 value.

Maybe others grasped this simple little difference in the fact that you need to evaluate on the boolean itself, rather than the value as depending upon the assignment method, the value for FALSE can have one of several true values.
25-Jan-2006 04:00
Just a supplement to johnjc-phpdoc's post:

This
if ( strpos($needle,$haystack) !== false )

is not the same as
if (!strpos($needle,$haystack) === false )

for the reason he states, namely, strpos does not evaluate to true, ever.
johnjc-phpdoc at publicinfo dot net
01-Nov-2005 09:38
The === and !== are not fully documented in either the Comparison Operator or Booleans type sections. They are talked about a bit more in the sections on strpos() and array_search() but they refer you to the section on Booleans for further information.

I am putting my contribution on === and !== in the Booleans section with pointers to it from the comment areas of other sections.

This refers only to the use of === and !== with functions like strpos() and array_search() which may a needle at character 0 in a string or element 0 in an array. Because the 0 returned by the function evaluates to == 'false' === and !== are used.  You can say
<?php if ( strpos($needle,$haystack) !== false ) { print "found it\n"; } ?>
and you can say
<?php if ( strpos($needle,$haystack) === false ) { print "didn't find it\n"; } ?>
but you cannot say
<?php if ( strpos($needle,$haystack) === true ) { print "found it \n"; } ?>
nor can you say
<?php if ( strpos($needle,$haystack) !== true ) { print "didn't find it\n"; } ?>

This is because strpos() and array_search do not return 'true' when successful and the numbers they return do not evaluate to === true.  So you cannot use 'true' in any way with these functions.

I frequently find myself adding string elements to an array as I find them and using the growing array as my record of what has already been done such as
<?php if ( array_search($needle,$haystack) !== false ) { print "done one of those already\n"; } ?>
or
<?php if ( array_search($needle,$haystack) === false ) { print "got a new one\n"; array_push($haystack,$needle) } ?>

The more natural way to say this would have been the other way around:
<?php if ( array_search($needle,$haystack) === true ) { print "done one of those already\n"; } ?>
or
<?php if ( array_search($needle,$haystack) !== true ) { print "got a new one\n"; array_push($haystack,$needle) } ?>
because you don't go around saying, "if this is not false", you say "if this is true".

But that won't work. Now I've had it explained to me it makes sense that the function doesn't return 'true' because it returns a number value instead. And given that === checks the type you can't have the number evaluate to '=== true'. But the result for the user of PHP is counter-intuitive and so deserves specific documenting.
x123 (at) bestof (dash) inter (dot) net
15-Nov-2004 12:24
another correction to the preceding "correction":
"as the documention states" is right,
"any non-empty string is true" is wrong : (bool) "0" === false !
(but "00" and "0.0" etc. are true!)

So watch out, you can NOT test for non-empty strings using e.g.

<?php
if (is_string($s))
  if (
$s) echo " '$s' is a non-empty string";
  else echo
" '$s' is an empty string"; // wrong for $s='0' !
else echo " $s is not a string ";
?>

indeed, for $s='0' this would print: " '0' is an empty string"
which is wrong, of course.
This is particularly "dangerous" in connection with MySQL
which prints FALSE by default as 0,
which comes back from a FORM POST as string '0',
while PHP prints FALSE as empty string (!);
a similar problem is to preserve a NULL value through a FORM post....
adama at NO-UBE dot augustinefam dot org
23-May-2003 10:13
Just a correction to the 29-Apr-2003 10:49 posting. The first section of the comment, where

 $myBool = true ;  print( $myBool ) ;
 is indistinguishable from
 print( "" ) ;
 likewise,
 $myBool = false ; print( $myBool ) ;
 is indistinguishable from
 print( 1 ) ;

is backwards. It should actually be

 $myBool = true ;  print( $myBool ) ;
 is indistinguishable from
 print( 1 ) ; //corrected
 likewise,
 $myBool = false ; print( $myBool ) ;
 is indistinguishable from
 print( "" ) ; //corrected

The posting makes a good point, though. Don't expect the contents of a string to mean something special. As the documentation states, any non-empty string is true, including "false" since it is simply a non-empty string.

<ТипыЦелые>
 Last updated: Tue, 15 Nov 2005