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

JavaScript must be enabled for certain features to work
* Required information
1000

Comments

No comments yet. Be the first!
(追記) (追記ここまで)
(追記) (追記ここまで)

AltStyle によって変換されたページ (->オリジナル) /