Sie sind auf Seite 1von 15

PHP: Booleanos - Manual

http://php.net/manual/es/language.types.boolea...

Downloads
Documentation
Get Involved
Help

Search
PHPKonf: Istanbul PHP Conference 2017
Getting Started
Introduction
A simple tutorial
Language Reference
Basic syntax
Types
Variables
Constants
Expressions
Operators
Control Structures
Functions
Classes and Objects
Namespaces
Errors
Exceptions
Generators
References Explained
Predefined Variables
Predefined Exceptions
Predefined Interfaces and Classes
Context options and parameters
Supported Protocols and Wrappers
Security
Introduction
General considerations
Installed as CGI binary
Installed as an Apache module
Session Security
Filesystem Security
Database Security
Error Reporting
Using Register Globals
User Submitted Data
Magic Quotes
Hiding PHP
Keeping Current
1 de 15

14/01/17 13:35

PHP: Booleanos - Manual

http://php.net/manual/es/language.types.boolea...

Features
HTTP authentication with PHP
Cookies
Sessions
Dealing with XForms
Handling file uploads
Using remote files
Connection handling
Persistent Database Connections
Safe Mode
Command line usage
Garbage Collection
DTrace Dynamic Tracing
Function Reference
Affecting PHP's Behaviour
Audio Formats Manipulation
Authentication Services
Command Line Specific Extensions
Compression and Archive Extensions
Credit Card Processing
Cryptography Extensions
Database Extensions
Date and Time Related Extensions
File System Related Extensions
Human Language and Character Encoding Support
Image Processing and Generation
Mail Related Extensions
Mathematical Extensions
Non-Text MIME Output
Process Control Extensions
Other Basic Extensions
Other Services
Search Engine Extensions
Server Specific Extensions
Session Extensions
Text Processing
Variable and Type Related Extensions
Web Services
Windows Only Extensions
XML Manipulation
GUI Extensions
Keyboard Shortcuts
?
This help
j
Next menu item
k
Previous menu item
gp
2 de 15

14/01/17 13:35

PHP: Booleanos - Manual

http://php.net/manual/es/language.types.boolea...

Previous man page


gn
Next man page
G
Scroll to bottom
gg
Scroll to top
gh
Goto homepage
gs
Goto search
(current page)
/
Focus search box
Nmeros enteros (Integers)
Introduccin
Manual de PHP
Referencia del lenguaje
Tipos
Change language:

Spanish

Edit Report a Bug

Booleanos
Este es el tipo ms simple. Un boolean expresa un valor que indica verdad.
Puede ser TRUE (verdadero) o FALSE (falso).

Sintaxis
Para especificar un literal de tipo boolean se emplean las constantes
FALSE. Ambas no son susceptibles a maysculas y minsculas.

TRUE

<?php
$foo=True;//asignaelvalorTRUEa$foo
?>

Usualmente, el resultado de un operador que devuelve un valor de tipo


boolean es pasado a una estructura de control.
<?php
//==esunoperadorquecompruebala
//igualdadydevuelveunbooleano
if($accion=="mostrar_version"){
echo"Laversines1.23";
}

3 de 15

14/01/17 13:35

PHP: Booleanos - Manual

http://php.net/manual/es/language.types.boolea...

//estonoesnecesario...
if($mostrar_separadores==TRUE){
echo"<hr>\n";
}
//...porquesepuedeescribirsimplemente:
if($mostrar_separadores){
echo"<hr>\n";
}
?>

Conversin a booleano
Para convertir explcitamente un valor al tipo boolean, use los amoldamientos
(bool) o (boolean). Sin embargo, en la mayora de casos es innecesario el
amoldamiento, ya que un valor ser convertido automticamente si un
operador, funcin o estructura de control requiere un argumento de tipo
boolean.
Vase tambin la Manipulacin de tipos.
Cuando se realizan conversiones a boolean, los siguientes valores se
consideran FALSE:
el boolean FALSE mismo
el integer 0 (cero)
el float 0.0 (cero)
el valor string vaco, y el string "0"
un array con cero elementos
un object con cero variables miembro (slo en PHP 4)
el tipo especial NULL (incluidas variables no establecidas)
objetos SimpleXML creados desde etiquetas vacas
Cualquier otro valor se considera como

TRUE

(incluido cualquier resource).

Advertencia
-1 se considera TRUE, como cualquier otro nmero distinto de cero (ya sea
negativo o positivo).
<?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)
?>

4 de 15

14/01/17 13:35

PHP: Booleanos - Manual

http://php.net/manual/es/language.types.boolea...

add a note

User Contributed Notes 19 notes


up
down
481
Fred Koschara
3 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

5 de 15

14/01/17 13:35

PHP: Booleanos - Manual

http://php.net/manual/es/language.types.boolea...

the expression where it is being used.

up
down
117
admin at eexit dot fr
8 years ago
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
?>

up
down
5
goran77 at fastmail dot fm
4 months 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.

6 de 15

14/01/17 13:35

PHP: Booleanos - Manual

http://php.net/manual/es/language.types.boolea...

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
down
33
terminatorul at gmail dot com
9 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
down
7
marklgr
1 year 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.

up
down
30
Wackzingo
8 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

7 de 15

14/01/17 13:35

PHP: Booleanos - Manual

http://php.net/manual/es/language.types.boolea...

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
down
28
artktec at gmail dot com
9 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)
/*

8 de 15

14/01/17 13:35

PHP: Booleanos - Manual

http://php.net/manual/es/language.types.boolea...

Note: normal casting rules apply so a !!"0" would evaluate to an === false
*/
?>

up
down
23
Steve
8 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
down
1
emanuelemicciulla[at]gmail[dot]com
2 years ago
A lot of people apparently looking for this:
<?php
$strictBool = filter_var($stringBool, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
if($boolFanOvr === null) { /*manage error*/};
?>
it's TRUE for "true" "True" "TRUE" "Yes" "1" and so on.
FALSE for "false" "0" "no" and so on.
it's NULL if string doesn't represent a valid boolean.

up
down
0
richie dot hayward at gmail dot com
7 months ago
Actually from a complete noob point of view 0 resulting in false makes sense as many
languages as I have been taught consider the value 1 as true and the value 0 as false a
simple boolean value.
So lets says you think you set a variable to 0 and some how or another through your
code this value has implicitly become and string instead of a int or boolean. Should
PHP now consider it to evaluate to false. I wouldn't think so but hey I'm a PHP noob so
perhaps I'm missing why you would ever want a "0" string to evaluate to true.

9 de 15

14/01/17 13:35

PHP: Booleanos - Manual

http://php.net/manual/es/language.types.boolea...

up
down
3
fyrye at torntech dot com
6 years ago
Since I haven't seen it posted.
Here is a function that you can use if you have a need to force strict boolean values.
Hopefully this will save someone some time from searching for similar.
<?php
function strictBool($val=false){
return is_integer($val)?false:$val == 1;
}
?>
Simply put, it verifies that the value passed is (bool)true otherwise it's false.
Examples:
__________________________________
<?php
$myBool = strictBool(true);
var_dump($myBool);
//returns (bool)true
$myar = array(0 => true);
$myBool = strictBool($myar[0]);
var_dump($myBool);
//returns (bool)true
$myBool = strictBool("hello");
var_dump($myBool);
//returns (bool)false
$myBool = strictBool(false);
var_dump($myBool);
//returns (bool)false
$myBool = strictBool(array(0 => "hello"));
var_dump($myBool);
//returns (bool)false
$myBool = strictBool(1);
var_dump($myBool);
//returns (bool)false
$myBool = strictBool();
var_dump($myBool);
//returns (bool)false
?>

up
down

10 de 15

14/01/17 13:35

PHP: Booleanos - Manual

http://php.net/manual/es/language.types.boolea...

1
geza at turigeza dot com
3 years ago
// someKey is a boolean true
$array = array('someKey'=>true);
// in the following 'false' string gets converted to a boolean true
if($array['someKey'] != 'false')
echo 'The value of someKey is '.$array['someKey'];
As a result the above will output nothing :)
if($array['someKey'] == 'false')
echo 'The value of someKey is '.$array['someKey'];
And the above will output
The value of someKey is 1
In short true == 'false' is true.

up
down
2
oscar at oveas dot com
6 years ago
Dunno if someone else posted this solution already, but if not, here's a useful and
function to convert strings to strict booleans.
Note this one only checks for string and defaults to the PHP (boolean) cast where e.g.
-1 returns true, but you easily add some elseifs for other datatypes.
<?php
function toStrictBoolean ($_val, $_trueValues = array('yes', 'y', 'true'),
$_forceLowercase = true)
{
if (is_string($_val)) {
return (in_array(
($_forceLowercase?strtolower($_val):$_val)
, $_trueValues)
);
} else {
return (boolean) $_val;
}
}
?>

up
down
1
mercusmaximus at yahoo dot com
6 years ago
Note that the comparison: (false == 0) evaluates to true and so will any value you set
to false as well (without casting).

11 de 15

14/01/17 13:35

PHP: Booleanos - Manual

http://php.net/manual/es/language.types.boolea...

up
down
1
Symbol
7 years ago
Just a side note, doesn't really matters, the reason -1 is true and not false is
because boolean type is treated as unsigned, so -1 would be for example, if it's
unsigned int32 translate to hex: 0xFFFFFFFF and back to decimal: 4294967295 which is
non-zero. there isn't really a "negative boolean". it's a binary thing. :o (since it
used to be a bit and then there was only 0 and 1 as an option)

up
down
1
wbcarts at juno dot com
8 years ago
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

12 de 15

14/01/17 13:35

PHP: Booleanos - Manual

http://php.net/manual/es/language.types.boolea...

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.

up
down
-4
ledadu at gmail dot com
6 years ago

13 de 15

14/01/17 13:35

PHP: Booleanos - Manual

http://php.net/manual/es/language.types.boolea...

up
down
-7
den
2 years ago

up
down
-8
Anonymous
9 years ago

14 de 15

14/01/17 13:35

PHP: Booleanos - Manual

http://php.net/manual/es/language.types.boolea...

add a note

Tipos
Introduccin
Booleanos
Nmeros enteros (Integers)
Nmeros de punto flotante
Cadenas de caracteres (Strings)
Arrays
Objetos
Recursos
NULO
Llamadas de retorno (Callbacks / Callables)
Seudotipos y variables usadas en esta documentacin
Manipulacin de tipos
Copyright 2001-2017 The PHP Group
My PHP.net
Contact
Other PHP.net sites
Mirror sites
Privacy policy

15 de 15

14/01/17 13:35

Das könnte Ihnen auch gefallen