Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Function return 0 vs false

Tags:

php

I have a PHP function which returns a number that can be zero or larger. For example:

public function returnVal($val1, $val2) {
  if ($val2 > $val1) return $val2 - $val1;
  else return false;
}

This is being used as:

if ($diff = $this->returnVal($a, $b)) // do something
else // don't

However when the difference is zero, i'd still like it to do something, however it seems to be detecting the zero as false rather than zero. I still need to know when it is false though.

I tried changing it to:

if (($val2 - $val1) == 0) return 'zero';
if ($val2 > $val1) return $val2 - $val1;
else return false;

Which does work, but seems a bit inelegant - surely there must be a better way?

Thanks

like image 557
stukerr Avatar asked Aug 03 '26 01:08

stukerr


1 Answers

With the variable assignment shortcut inside of an if-statement, PHP uses loose-type comparisons and type-juggles things like 0, null, and other false-y values to false. You must use use the explicit === and !== comparisons to ensure that the comparison is of the exact same type (without type-juggling):

$diff = $this->returnVal($a, $b);
if ($diff !== false) // do something
else // don't

See this reference for all of the comparison conditions that could occur from using simple ==, =, or != comparisons.

Alternative from @MrLlama:

if (($diff = $this->returnVal($a, $b)) !== false) // do something
else // don't
like image 54
sjagr Avatar answered Aug 05 '26 19:08

sjagr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!