2

I'm running the following function and want to check if a value is NULL or '', but it seems to react the same for both. This prints C1C2. How can I get it to print B1C1C2? Should I use isset() somehow?

function title($a = NULL, $b = NULL, $c = NULL) {
    if( $a != NULL )
    {
        echo 'A1';
        if( $a != '' )
        {
            echo 'A2';
        }
    }
    if( $b != NULL )
    {
        echo 'B1';
        if( $b != '' )
        {
            echo 'B2';
        }
    }
    if( $c != NULL )
    {
        echo 'C1';
        if( $c != '' )
        {
            echo 'C2';
        }
    }
}

title(NULL, '', 'C');
3
  • 1
    Just use !isnull($a) or !empty($a) Commented Jun 13, 2018 at 18:26
  • 2
    @GrumpyCrouton maybe you meant is_null() Commented Jun 13, 2018 at 18:31
  • @JulianDavid That I did, thank you :) Commented Jun 13, 2018 at 18:33

2 Answers 2

3

If you just check for the value of the variable you will get true whether null or an empty string (''):

null == ''; // 1 (true)

You also need to check for type:

null === ''; // (false)

So instead of:

if( $a != NULL )

Run:

if( $a !== NULL )

Which will also check for type; '' is a string - not null type.


Rearranged function:

function title($a = NULL, $b = NULL, $c = NULL) {
    if( $a !== NULL )
    {
        echo 'A1';
        if( $a !== '' )
        {
            echo 'A2';
        }
    }
    if( $b !== NULL )
    {
        echo 'B1';
        if( $b !== '' )
        {
            echo 'B2';
        }
    }
    if( $c !== NULL )
    {
        echo 'C1';
        if( $c !== '' )
        {
            echo 'C2';
        }
    }
}

title(NULL, '', 'C'); // outputs: B1C1C2
Sign up to request clarification or add additional context in comments.

Comments

1

Be careful because ...

if(null == 0) echo "yes"; else echo "nope"; //prints yes
if(null === 0) echo "yes"; else echo "nope"; //prints no

So always use triple equals (=== or !==) instead of double equals (== or !=) in order to avoid this issue.

But the most appropriate way would be to use the "is_null()" PHP builtin function which returns true or false.

if(is_null(0)) echo "yes"; else echo "nope"; //prints nope

So we have ...

function title($a = NULL, $b = NULL, $c = NULL) {
    if(!is_null($a)) // using is_null builtin function
        echo 'A1';
        if($a !== '')// not !=, because 0!='' is false
            echo 'A2';
    if(!is_null($b))
        echo 'B1';
        if($b !== '')
            echo 'B2';
    if(!is_null($c))
        echo 'C1';
        if($c !== '')
            echo 'C2';
}

title(NULL, '', 'C'); // prints B1C1C2

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.