Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

nolros's avatar
Level 23

LOW PRIORITY - PHP Question - null or false,?

Are there any guidelines as to when to use null vs. false? Should I link them to types? Example, with my Lang method below:

I know I can test for any state, but wondering if there is a best practice?

Also, is best practice when testing to Boolean to actually check for 'true and false' i.e.

// the way I do it today
if( $value ) //check if false or true

// wondering if it should explicit
if( $value === 'false' )

I ask as explicit seems to be good for the following reasons Refactorability Consistency Protecting / redundancy

    /**
     * @param   array $values
     * @return  bool
     */
    private static function getMessage( array $values = array() )
    {
        $key        = null;

        $key        = self::setKey( $values[0] );

        if( ! is_null( $key ) )
        {
            if( isset( $value[1] ) ) $key = $key . $values[1];

            if( Lang::has( $key ) )  return Lang::get( $key  );

        }

        return false;

    }
0 likes
1 reply
jwondrusch's avatar
Level 1

It depends on your needs. There's nothing wrong with using your current method. In my day to day, I find myself using === and !== when I need a strict comparison. For example, some PHP functions return 0 as a valid response:

$val = strpos( 'abc', 'a' ); // returns 0
if ($val) { // This would never execute }

$val = strpos( 'abc', 'a' ); // returns 0
if ($val !== false) { // This would execute }

So in the end, I think it depends on context and personal coding style. It's pretty common to see if ($var) {}, but using more strict operations makes your code a bit more explicit, which is often valuable down the line.

1 like

Please or to participate in this conversation.