Markus Kottländer
Markus Kottländer

Reputation: 8268

if statement says true to a null variable

What is happening here? Is it to late for my brain?

I have a php file containing exaclty the code below.

<?php

$foo = 'foo';

$bar = null;

switch ($foo) {
    default:
    case 'foo':
        if ($bar) {
            echo 'true';
        } else {
            echo 'false';
        }
}

Prints true when run in the browser but false when run on command line... HOW? I noticed when I remove the line default: it works, but how should this whole switch statement be related to this? It's still a simple if (null) { doing this anyway }

PHP 7.0.13 Apache/2.4.18

And yes... I cleared my browser cache, hit ctrl+f5... I even changed the scripts file name.

UPDATE: After making changes to this simple file... (just adding whitespaces to the end) and hitting f5 in the browser it says false once but than true again... no matter what I do. I really don't get it.

UPDATE: My PHP version just got updated from 7.0.13 to 7.0.15. Guess what... still the same output:

Apache/Browser: true

Console: false

Upvotes: 3

Views: 128

Answers (1)

nwilging
nwilging

Reputation: 83

For this you can use isset

<?php
$foo = 'bar';

$bar = null;

switch ($foo) {
    default:
    case 'bar':
        if (isset($bar)) {
            echo "true";
            die();
        } else {
            echo "false";
            die();
        }
}

This code will echo false.

You could also use a double not operator:

<?php
$foo = 'bar';

$bar = null;

switch ($foo) {
    default:
    case 'bar':
        if (!!$bar) {
            echo "true";
            die();
        } else {
            echo "false";
            die();
        }
}

The problem with your default case

In the code you provided (and the code I re-quoted), you will be hitting case 'bar' every time, no matter what $foo is set to.

<?php
$foo = 'notbar';

$bar = null;

switch ($foo) {
    default:
    case 'bar':
        if (!!$bar) {
            echo "true";
            die();
        } else {
            echo "false";
            die();
        }
}

This code will still echo false.

What you should do is include a break in the default case.

<?php
$foo = 'notbar';

$bar = null;

switch ($foo) {
    default:
        echo "default";
        break;
    case 'bar':
        if (!!$bar) {
            echo "true";
            die();
        } else {
            echo "false";
            die();
        }
        break;
}

This code will echo default and nothing else.

Upvotes: 1

Related Questions