Programming Tutorials

Function to force strict boolean values in PHP

By: Fyrye in PHP Tutorials on 2011-04-08  

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





Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in PHP )

__autoload() METHOD in PHP

Opening a Remote File in PHP

Function to force strict boolean values in PHP

Installing PHP with Apache 2.x on HP UX 11i and configuring PHP with Oracle 9i

Building PHP with Apache2 on SuSE Professional 9.1/9.2

Cannot load /usr/local/apache/libexec/libphp4.so into server: ld.so.1:......

Setting up PHP in Windows 2003 Server IIS7, and WinXP 64

error: "Service Unavailable" after installing PHP to a Windows XP x64 Pro

Running different websites on different versions of PHP in Windows 2003 & IIS6 platform

Installing PHP with nginx-server under windows

Warning: session_start(): open .... failed - PHP error

Convert IP address to integer and back to IP address in PHP

Function to return number of digits of an integer in PHP

Function to sort array by elements and count of element in PHP

Floating point precision in PHP

Latest Articles (in PHP)