1

I have a variable which always contains one of these two cases:

  • false
  • A number (it can be also 0)

My variable in reality is this:

$index = array_search(1, array_column($var, 'box'));
//=> the output could be something like these: false, 0, 1, 2, ...

Now I want to detect $index is false or anything else. How can I implement such a condition?

It should be noted none of these doesn't work:

if ( empty($index) )   { }
if ( !isset($index) )  { }
if ( is_null($index) ) { }

And I want this condition:

if ( ? ) { // $index is false } else { // $index is a number (even 0) }
stack
  • 10,280
  • 19
  • 65
  • 117

2 Answers2

1

Use the === operator...

if(false == 0)

That will cast 0 to false and you get false == false

if(false === 0)

That does not cast and you get false compared to zero, which is not the same.

For not equal to, use !== instead of ===

kainaw
  • 4,256
  • 1
  • 18
  • 38
1

You can use the PHP identical operator ===:

if (false === 0)

This will return false if they are of the same type. Unlike == where type juggling occurs, false is not identical to 0.

if ($index === false) { 
    // $index is false
} else {
    // $index is a number (even 0)
}

More information on the difference between the identical operator === and the comparison operator ==: How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?

Community
  • 1
  • 1
Panda
  • 6,955
  • 6
  • 40
  • 55