Function to force strict boolean values in PHP
By: Fyrye
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
?>
Archived Comments
Comment on this tutorial
- Data Science
- Android
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Related Tutorials
PHP convert string to lower case
PHP code to write to a CSV file for Microsoft Applications
PHP code to write to a CSV file from MySQL query
PHP code to import from CSV file to MySQL
Password must include both numeric and alphabetic characters - Magento
Error: Length parameter must be greater than 0
PHP file upload prompts authentication for anonymous users
PHP file upload with IIS on windows XP/2000 etc
Multiple File Upload in PHP using IFRAME
Resume or Pause File Uploads in PHP
Exception in module wampmanager.exe at 000F15A0 in Windows 8