PHP Doku:: Prüft, ob eine Variable vom Typ boolean ist - function.is-bool.html

Verlauf / Chronik / History: (1) anzeigen

Sie sind hier:
Doku-StartseitePHP-HandbuchFunktionsreferenzVariablen- und typbezogene ErweiterungenVariablenbehandlungFunktionen zur Behandlung von Variablenis_bool

Ein Service von Reinhard Neidl - Webprogrammierung.

Funktionen zur Behandlung von Variablen

<<is_array

is_callable>>

is_bool

(PHP 4, PHP 5)

is_bool Prüft, ob eine Variable vom Typ boolean ist

Beschreibung

bool is_bool ( mixed $var )

Prüft, ob die gegebene Variable ein Boolean ist.

Parameter-Liste

var

Die zu untersuchende Variable.

Rückgabewerte

Gibt TRUE zurück, wenn var vom Typ boolean ist, ansonsten FALSE.

Beispiele

Beispiel #1 is_bool()-Beispiele

<?php
$a 
false;
$b 0;

// Da $a ein Boolean ist, wird true zurückgegeben
if (is_bool($a) === true) {
    echo 
"Ja, das ist ein Boolean";
}

// Da $b kein Boolean ist, wird false zurückgegeben
if (is_bool($b) === false) {
    echo 
"Nein, dies ist kein Boolean";
}
?>

Siehe auch

  • is_float() - Prüft, ob eine Variable vom Typ float ist
  • is_int() - Prüft, ob eine Variable vom Typ int ist
  • is_string() - Prüft, ob Variable vom Typ string ist
  • is_object() - Prüft, ob eine Variable vom Typ object ist
  • is_array() - Prüft, ob die Variable ein Array ist


8 BenutzerBeiträge:
- Beiträge aktualisieren...
kim at steinhaug dot com
26.08.2009 19:48
Seems this is a most wanted function, so here is my version of it. I have been using this one for several years no and it works perfect for my needs. I have added "sloppy" human logic to it, and you could easily extend to your flavour. Like in norway some would use "ja" and "nei" instead of "yes" and "no".

<?php
/**
 * Checks a variable if it is true or false, humanlike.
 * We account for values as 'on', '1', '' and so on.   
 * Finally, for some reare occurencies we account with 
 * crazy logic to fit some arrays and objects.         
 *                                                     
 * @author Kim Steinhaug, <kim@steinhaug.com>          
 * @param mixed $var, the variable to check            
 *                                                     
 * Example:                                            
 * $test = 'true';                                     
 * if(_bool($test)){ echo 'true'; } else { echo 'false'; }
 */
function _bool($var){
  if(
is_bool($var)){
    return
$var;
  } else if(
$var === NULL || $var === 'NULL' || $var === 'null'){
    return
false;
  } else if(
is_string($var)){
   
$var = trim($var);
    if(
$var=='false'){ return false;
    } else if(
$var=='true'){ return true;
    } else if(
$var=='no'){ return false;
    } else if(
$var=='yes'){ return true;
    } else if(
$var=='off'){ return false;
    } else if(
$var=='on'){ return true;
    } else if(
$var==''){ return false;
    } else if(
ctype_digit($var)){
      if((int)
$var)
        return
true;
        else
        return
false;
    } else { return
true; }
  } else if(
ctype_digit((string) $var)){
      if((int)
$var)
        return
true;
        else
        return
false;
  } else if(
is_array($var)){
    if(
count($var))
      return
true;
      else
      return
false;
  } else if(
is_object($var)){
    return
true;// No reason to (bool) an object, we assume OK for crazy logic
 
} else {
    return
true;// Whatever came though must be something,  OK for crazy logic
 
}
}
?>
moty66 at gmail dot com
20.08.2009 23:18
Here is the function which I use when pasring boolean variables from config files

<?php
function boolVal($var) {
    switch (
$var) {
        case
$var == true:
        case
$var == 1:
       
// case $var == '1': // no need for this, because we used
                             // $val == 1 not $var === 1
       
case strtolower($var) == 'true':
        case
strtolower($var) == 'on':
        case
strtolower($var) == 'yes':
        case
strtolower($var) == 'y':
           
$out = 1;
            break;
        default:
$out = 0;
    }
   
    return
$out;
}

?>

I am woundering why php does not have a function to do this

Motaz Abuthiab
sam+nospam at samuellevy dot com
2.02.2009 1:30
Just another little function which doesn't exist yet, but I find mighty useful, especially when working with AJAX and APIs.

<?php
/** Checks a variable to see if it should be considered a boolean true or false.
 *     Also takes into account some text-based representations of true of false,
 *     such as 'false','N','yes','on','off', etc.
 * @author Samuel Levy <sam+nospam@samuellevy.com>
 * @param mixed $in The variable to check
 * @param bool $strict If set to false, consider everything that is not false to
 *                     be true.
 * @return bool The boolean equivalent or null
 */
function boolval($in, $strict=false) {
   
$out = null;
   
// if not strict, we only have to check if something is false
   
if (in_array($in,array('false', 'False', 'FALSE', 'no', 'No', 'n', 'N', '0', 'off',
                          
'Off', 'OFF', false, 0, null), true)) {
       
$out = false;
    } else if (
$strict) {
       
// if strict, check the equivalent true values
       
if (in_array($in,array('true', 'True', 'TRUE', 'yes', 'Yes', 'y', 'Y', '1',
                              
'on', 'On', 'ON', true, 1), true)) {
           
$out = true;
        }
    } else {
       
// not strict? let the regular php bool check figure it out (will
        //     largely default to true)
       
$out = ($in?true:false);
    }
    return
$out;
}
?>

It may be pretty inefficient, but it does the job.
bb at kingdom dot cjb dot net
27.06.2007 11:57
@ emmanuel del grande

You don't need to break when you return...

function bool($var) {
    switch (strtolower($var)) {
        case ("true"): return true;
        case ("false"): return false;
        default: die("whatever you want it to tell");
    }
}
kevin at metalaxe dot com
5.06.2007 10:32
@ emanueledelgrande at email dot it

http://us.php.net/manual/en/language.types.type-juggling.php

(bool) or (boolean) is allowed for type casting a variable. No function like intval, etc but the functionality exists.
emanueledelgrande at email dot it
22.05.2007 18:12
I think there's a hole in the PHP typecasting methods:
you have the (int) function, the (float) function and the (string) function, but no function to force a string variable into the boolean type.

It's obvious that forcing unconditionally the type of variables into arrays and objects is inappropriate, but boolean type is the most basic one for each programming language, that's why I guessed that a (bool) function already existed.

Moreover, with the increasing trend of RSS data streaming, the parsing of an XML string into an object often requires to typecast as boolean values the content of XML tags, normally returned as string by the object method get_content().

I wrote the following function, which also uses a "native PHP style" error message:

<?php
// strings tyecasting as boolean values:
function bool($var) {
    switch (
strtolower($var)) {
        case (
"true"):
            return
true;
            break;
        case (
"false"):
            return
false;
            break;
        default:
            die(
"<br />\n<b>Warning:</b> Invalid argument supplied for ".__FUNCTION__." function in <b>".__FILE__."</b> on line <b>".__LINE__."</b>: the argument can contain only 'true' or 'false' values as a string.<br />\n");
    }
}
?>

Here it is a small example:

<?php
$xmlResponse
= "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
$xmlResponse .= "<Result>";
$xmlResponse .= "<AuthError>false</AuthError>";
$xmlResponse .= "<TransferStatus>true</TransferStatus>";
$xmlResponse .= "</Result>";

if (!
$responseDoc = domxml_open_mem($xmlResponse, DOMXML_LOAD_PARSING, $XmlParsingError)) {
    echo
"Error while parsing the XML string:<br />".print_r($XmlParsingError, TRUE);
} else {
   
$ResultNode = $responseDoc->get_elements_by_tagname('Result');
   
   
$AuthError = $ResultNode[0]->get_elements_by_tagname('AuthError');
   
$auth_error = bool($AuthError[0]->get_content());
   
   
$TransferStatus = $ResultNode[0]->get_elements_by_tagname('TransferStatus');
   
$transfer_status = bool($TransferStatus[0]->get_content());
   
    if (!
$auth_error) { echo "Auth OK<br />"; } else { echo "Auth error<br />"; }
    if (
$transfer_status) { echo "Transfer OK<br />"; } else { echo "Transfer error<br />"; }
}

?>

It would be useful this function to be implemented in the core of PHP5.

21.04.2006 13:12
Small caveat to rh's post: back in PHP 3, "0" would be considered non-empty (i.e., empty would return false), even though (bool) on "0" would also evaluate to false; thus, they would not be complete opposites for someone using PHP 3.
rh at richardhoward dot net
22.05.2005 20:17
punkpuke is wrong here; what he means to say is that empty($x) is the opposite of (bool)$x.  is_bool($x) returns true where $x === false.



PHP Powered Diese Seite bei php.net
The PHP manual text and comments are covered by the Creative Commons Attribution 3.0 License © the PHP Documentation Group - Impressum - mail("TO:Reinhard Neidl",...)