In PHP, there are several ways to check whether a value is true, or similar:
true === $v
, only works for booltrue == $v || !!$v
, works with int and string, but a non empty array can also be considered true1 == $v
, works with bool, int, string and always false with arrays
Personally, I feel partial to 3. Especially when working with legacy platforms such as WordPress where a bool value usually comes from the database in the form of a string number, but sometimes cast number or bool.
But I also read in the WordPress Code Standard that loose comparison (==) should only be used "when absolutely necessary".
The community seem to feel very strongly that loose comparison is something that should always be avoided. At the time, casting to bool (!!$v) seem to be pretty uncontroversial, though logically equivalent to loose comparison.
The following is a correct example in the WP Code Standard:
$data = $wpdb->get_var( '...' );
if ( $data ) /* loosley compared to true ?!?!?! */ {
// Use $data.
}
Is there a rationale for why I should not use loose comparison with number for values similar to true or false?
"3" == 3