note 94503 deleted from language.types.boolean by danbrown

From: Date: Mon, 09 Nov 2009 16:24:57 +0000
Subject: note 94503 deleted from language.types.boolean by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-162664@lists.php.net to get a copy of this message
Note Submitter: Echo ---- 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.

« previous php.notes (#162664) next »