note 94503 added to language.types.boolean
| From: | Echo at osu1 dot php dot net | Date: | Mon, 09 Nov 2009 14:33:58 +0000 |
| Subject: | note 94503 added to language.types.boolean | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-162659@lists.php.net to get a copy of this message | ||
In response to [russell dot harper at springboardnetworks dot com], the following code maybe used:
<?php
function to_bool( $var) {
if( is_string( $var)) {
$firstchar = ord( $var[0]);
if( $firstchar == ord("-") || $firstchar == ord("+") || ($firstchar
>= ord("0") && $firstchar <= ord("9"))
$var = (int) $var;
else
return true;
}
return (bool) $var;
}
var_dump( // These all return FALSE
to_bool( 0),
to_bool( false),
to_bool( "0"),
to_bool( "0.0"),
to_bool( "")
);
var_dump( // These all return TRUE
to_bool( 1),
to_bool( true),
to_bool( "1"),
to_bool( "-1"),
to_bool( "true"),
to_bool( "false")
);
?>
The function can be easily changed to respond to strings like "false" and "no"
correctly if so needed.
----
Server IP: 92.48.74.199
Probable Submitter: 129.67.110.224
----
Manual Page -- http://www.php.net/manual/en/language.types.boolean.php
Edit -- https://master.php.net/note/edit/94503
Del: integrated -- https://master.php.net/note/delete/94503/integrated
Del: useless -- https://master.php.net/note/delete/94503/useless
Del: bad code -- https://master.php.net/note/delete/94503/bad+code
Del: spam -- https://master.php.net/note/delete/94503/spam
Del: non-english -- https://master.php.net/note/delete/94503/non-english
Del: in docs -- https://master.php.net/note/delete/94503/in+docs
Del: other reasons-- https://master.php.net/note/delete/94503
Reject -- https://master.php.net/note/reject/94503
Search -- https://master.php.net/manage/user-notes.php