Inteiros> <Introdução
Last updated: Fri, 02 Jan 2009

Booleanos

Este é o tipo mais fácil. Um booleano expressa um valor de verdade. Ele pode ser TRUE ou FALSE.

Nota: O tipo booleano foi introduzido no PHP 4.

Sintaxe

Para especificar um literal booleano, use as palavras chave TRUE ou FALSE. Ambas são insensitivas ao caso.

<?php
$foo 
True// assimila o valor TRUE para $foo
?>

Usualmente você pode utilizar algum tipo de operador que retorne um valor booleano, e passá-lo para uma estrutura de controle.

<?php
// == Ã© um operador que testa
// igualdade e retorna um booleano
if ($action == "mostrar_versao") {
    echo 
"A versão Ã© 1.23";
}

// isto não Ã© necessário ...
if ($exibir_separadores == TRUE) {
    echo 
"<hr>\n";
}

// ... porque você pode simplesmente escrever isso:
if ($exibir_separadores) {
    echo 
"<hr>\n";
}
?>

Convertendo para booleano

Para converter explicitamente um valor para booleano, utilize-se dos modificadores (bool) ou (boolean). Entretanto, na maioria dos casos, você não precisa utilizar o modificador, desde que qualquer valor será convertido automaticamente se um operador, função ou estrutura de controle requerer um argumento booleano.

Veja também Manipulação de tipos.

Quando convertendo para booleano, os seguintes valores são considerados FALSE:

Qualquer outro valor é considerado TRUE (incluindo qualquer recurso).

Aviso

-1 é considerado TRUE, como qualquer valor não zero (negativos ou positivos)!

<?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)
?>



Inteiros> <Introdução
Last updated: Fri, 02 Jan 2009
 
User Contributed Notes
Booleanos
admin at eexit dot fr
04-Nov-2008 06:27
Beware of certain control behavior with boolean and non boolean values :

<?php
// Consider that the 0 could by any parameters including itself
var_dump(0 == 1); // false
var_dump(0 == (bool)'all'); // false
var_dump(0 == 'all'); // TRUE, take care
var_dump(0 === 'all'); // false

// To avoid this behavior, you need to cast your parameter as string like that :
var_dump((string)0 == 'all'); // false
?>
wbcarts at juno dot com
06-Oct-2008 03:59
CODING PRACTICE...

Much of the confusion about booleans (but not limited to booleans) is the fact that PHP itself automatically makes a type cast or conversion for you, which may NOT be what you want or expect. In most cases, it's better to provide functions that give your program the exact behavior you want.
<?php

function boolNumber($bValue = false) {                      // returns integer
 
return ($bValue ? 1 : 0);
}

function
boolString($bValue = false) {                      // returns string
 
return ($bValue ? 'true' : 'false');
}

$a = true;                                                  // boolean value
echo 'boolean $a AS string = ' . boolString($a) . '<br>';   // boolean as a string
echo 'boolean $a AS number = ' . boolNumber($a) . '<br>';   // boolean as a number
echo '<br>';

$b = (45 > 90);                                             // boolean value
echo 'boolean $b AS string = ' . boolString($b) . '<br>';   // boolean as a string
echo 'boolean $b AS number = ' . boolNumber($b) . '<br>';   // boolean as a number
echo '<br>';

$c = boolNumber(10 > 8) + boolNumber(!(5 > 10));            // adding booleans
echo 'integer $c = ' . $c .'<br>';

?>
Results in the following being printed...

 boolean $a AS string = true
 boolean $a AS number = 1

 boolean $b AS string = false
 boolean $b AS number = 0

 integer $c = 2

In other words, if we know what we want out of our program, we can create functions to accommodate. Here, we just wanted 'manual control' over numbers and strings, so that PHP doesn't confuse us.
maykelsb [ta] yahoo [tod] com [tod] br
31-Jan-2008 09:54
At http://www.blueshoes.org/en/developer/syntax_exam/, is available a test where you can try your knowledge about boolean expressions. Hope it helps!
Wackzingo
27-Jan-2008 12:39
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.

$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.
Steve
15-Jan-2008 09:00
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.
Anonymous
06-Jan-2008 01:05
Note that the symbolic constants TRUE and FALSE are treated differently.  I was told that this is a feature, not a bug.

echo false ;
echo (false) ;
echo false+false ;
echo (false+false) ;
echo intval(false) ;
echo '"'.false.'"' ;

echo true ;
echo (true) ;
echo true+true ;
echo (true+true) ;
echo intval(true) ;
echo '"'.true.'"' ;

should produce

00000"0"11221"1"

but instead produces

000""11221"1"

In other words, the only way to output the underlying zero or use it in a string is to use 'false+false' or pass it through intval().  No such tricks are required to get at the 1 that underlies true.

The whole idea of symbolic constants is that the underlying value *always* replaces them during translation, and thus anywhere you would otherwise have to use some obscure "magic number" such as 191, you can use a symbolic constant that makes sense, such as TOTAL_NATIONS. 

Exactly what php gets out of breaking this rule was not explained to me.
artktec at gmail dot com
27-Sep-2007 01:37
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
*/
?>
openspecies
13-Jul-2007 12:22
function is_odd($x) { return ($x & 1); //integer }
function is_even($x) { return (!($x & 1)); //integer }

if(is_even(10) === TRUE)
  // NO

function is_odd($x) { return (bool) ($x & 1); //boolean }
function is_even($x) { return  (bool) (!($x & 1)); //boolean }

if(is_even(10) === TRUE)
  // YES

$str = 'Hello World!';

if($str === TRUE)
  // ecetera

@+
Schraalhans Keukenmeester
23-May-2007 02:03
Re: andy at txtnation dot com
<quote> The braces are of course optional </quote>

Nothing optional about the 'braces'  here.
'(  )' are parentheses. '{  }' are braces. But we get the point.

<?php
$num
= 10;
$isEven = !($num % 2);
echo (
$isEven) ? 'Even' : 'Odd';
//outputs : Even
$isEven = !$num % 2;
echo (
$isEven) ? 'Even' : 'Odd';
//outputs : Odd (with ANY number != 0 !!)
?>

Operator precedence and implicit casts at work:
$num = 10;
!$num       => (implicit cast to bool) $num: (bool) 10 = true
!true       => negate true : false
false % 2   => (implicit cast to int) false : (int) false = 0
0 % 2       => remainder of 0 intdiv 2 : 0
$isEven = 0 => integer assignment : 0
($isEven) ? => (implicit cast to bool) 0 : (bool) 0 = false
echo (false) ? 'Even' : 'Odd' => condition false : 'Odd'

Wether or not PHP actually performs the (bool) casts under the hood is irrelevant to the outcome here.
terminatorul at gmail dot com
29-Apr-2007 06:21
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.
12-Mar-2007 12:45
Jasper probably meant:
$a = 2;
$b = 3;
$aBiggerThanB = $a > $b;
andy at txtnation dot com
25-Feb-2007 02:31
Re: comment from jasper at jtey dot com

It is better to not explicitly test for default values. PHP knows the default values, and so should any programmer worth her/his salt.

Same example rewritten:

<?php
$num
= 10;
$isEven = !($num % 2);
?>

The braces are off course optional.
jasper at jtey dot com
05-Jun-2006 04: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 (corrected)
$c = "u";
$isVowel = $c == "a"|| $c == "e"|| $c == "i"|| $c == "o"|| $c == "u";
?>

Inteiros> <Introdução
Last updated: Fri, 02 Jan 2009