From Mexico City to Harvard
Ever seen or written this PHP code?
function foo( $foo ) {
// magic
if ( $foo ) // $foo is not bool
return true;
else
return false;
}
So you want to return a boolean value (true/false) but $foo isn’t a bool so you can’t return it directly.
Option 1, cast to boolean:
function foo( $foo ) {
// magic
return (boolean) $foo;
}
Option 2, cast to “bool” (shortcut):
function foo( $foo ) {
// magic
return (bool) $foo;
}
Option3, doublebang:
function foo( $foo ) {
// magic
return !!$foo;
}
The first ! (the “not” operator) casts $foo to a negative bool, and the second one flips it back to the bool representation of its original value.
And of course if you want to return true when the variable evaluates as false, you can just do:
function foo( $foo ) {
// magic
return !$foo;
}
Appologies to anyone who has read this far and was expecting pornography.
links for 2008-01-24 | a minor technicality
July 20th, 2008 at 7:26 pm
[…] Doublebang « Mark on WordPress (tags: php wordpress) Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages. […]
slutratry
July 20th, 2008 at 7:27 pm
http://www.google.com
http://www.yahoo.com
http://www.msn.com
Paris Exposed - Paris Hilton Sex Tape
July 20th, 2008 at 7:28 pm
Uncensored Paris Hilton sex tape point
Paris Exposed - Paris Hilton Sex Tape
vlad
July 20th, 2008 at 7:29 pm
I realize this is completely off-topic, but is it possible to order front page posts - last commented on top? And if it is possible, (there is no plugin-I checked) what would writing a this kind of plugin include?
Jack
July 20th, 2008 at 7:30 pm
so guys.. gangbang.. em.. what is it?
Maja
July 20th, 2008 at 7:31 pm
… I was so disappointed…
dlab
July 20th, 2008 at 7:32 pm
i got here because i thought it referred to Max/MSP
Mark Steel
July 20th, 2008 at 7:33 pm
Err, oops. I meant n-blue. Sorry. (Of course, I’d throw a missing “s” up there if I could edit, too)
Mark Steel
July 20th, 2008 at 7:34 pm
rxbbx: Now, now, “gang” suggest more than two … heh
Aja
July 20th, 2008 at 7:35 pm
@n-blue: Now, I know. ROFL
@Viper007Bond: return !empty($foo); would actually produce the same result, the ternary op just makes it explicit and redundant. Besides, !! is still shorter than !empty().
rxbbx
July 20th, 2008 at 7:36 pm
Nice.. fun
n-blue
July 20th, 2008 at 7:37 pm
@Aja
More familiar to “Gangbang”?
Ozh
July 20th, 2008 at 7:38 pm
Someone fancying an Obfuscated PHP Contest like Perl had?
scott47
July 20th, 2008 at 7:39 pm
A programmer I see!!! I took two years of computer programming in my schooling. It helped me a lot, sometimes I would use the software to create simple games or to figure out my homework =]
http://scott47.wordpress.com/
Top Posts « WordPress.com
July 20th, 2008 at 7:40 pm
[…] Doublebang Ever seen or written this PHP code? […]