0

In PHP, there are several ways to check whether a value is true, or similar:

  1. true === $v, only works for bool
  2. true == $v || !!$v, works with int and string, but a non empty array can also be considered true
  3. 1 == $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
  • 1
    What exactly is your question? There is no best way. You have listed plenty of options (more than I knew); choose the one that fits the situation best. As to why loose comparison should be avoided: you'll find tons of reasoning online. I personally prefer knowing the incoming data well enough so that I don't have to rely on loose comparison. Not because casting to bool is bad in and of itself, but because not knowing your data types is grounds for many bugs.
    – marstato
    Oct 13, 2022 at 19:57
  • Sorry for unclear question. How about "Why is loose comparison operators banned in most code standards, when bool casting is not?"? Oct 14, 2022 at 8:51
  • Casting to bool and loosely comparing to a boolean is essentially the same thing. Loose comparison against another data type has more caveats, e.g. "3" == 3
    – marstato
    Oct 14, 2022 at 17:44

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.