-1

I have a table of codes in a database. One of the codes has the id of 0.

I'm making a search function and I want one of the filters to be the codes, but it's optional. So, I need to differentiate between "0" and null in an if statement.

Here is one idea that looks to me like it would work...

if ( 0 < (int)$input['code'] or false !== strpos($input['code'], "0") ){
    // filter the search with the code
}

From this answer to a general question there are not that many differences between 0 and null. isset() might be one but empty() will not work. I'm not absolutely sure if the input is null or "" after it has been processed, I think it may be "". If this is the case, isset() will not work either.

Is there a better way to differentiate between 0 and null/""?

sdexp
  • 756
  • 4
  • 18
  • 36
  • 1
    How about `$input['code'] === 0` for comparing with 0 and `$input['code'] === null` for comparing with `null`. – DevK Apr 26 '18 at 21:31
  • 1
    [**`isset()`**](http://php.net/manual/en/function.isset.php) will work just fine. If it's `0`, it's set. This can be seen [**here**](https://3v4l.org/TU3G6). – Obsidian Age Apr 26 '18 at 21:32
  • `is_null($input['code'])` or as others have said `null === $input['code']` constants should always be on the left in a condition because it prevents mistakes like this `if($input['code'] = null)` where it does assignment, this will fail with an error `if(null = $input['code'])` whereas the other won't, just in case anyone wondered why you often see the constants on the left.... :-p – ArtisticPhoenix Apr 26 '18 at 21:47
  • @ArtisticPhoenix you should not use 'should'. That's a matter of taste. – Progrock Apr 26 '18 at 22:06
  • Are all the other codes numbers as well? – Don't Panic Apr 26 '18 at 22:19
  • @Progrock - Granted it's an Opinion. – ArtisticPhoenix Apr 26 '18 at 22:26

1 Answers1

1

Use the === and !== operators for these sort of comparisons. These "strict" or "true" comparison. These operators were invented specifically to help deal with the sort of comparison problems you've described.

You also might be interested in the PHP comparison tables. This docs page runs through a lot of the various edge cases in PHP equality.

Alana Storm
  • 164,128
  • 91
  • 395
  • 599