Alex-none
Alex-none

Reputation: 133

Return integer 0

Sorry for bad english , used Google.translate

There is a code that returns a value to a int, if set . Otherwise it returns false

if (isset($this->variable))
   return intval ($this->variable);
else
   return false;

On the receiving side condition

if ($return_value) {
   // Here code
}

The problem is that if the returned value is 0, this is false, and the code is executed . But as the value of 0 is also important to me . If returned as a string , it is still treated as false.

define ('false', 'value') does not work.

Introduced his constant for this , but you have to rewrite a bunch of code for additional testing

(if($return_value! == my_false_constant)

That is not quite satisfied.

What options are there to solve this problem ?

Upvotes: 1

Views: 636

Answers (4)

Abed Hawa
Abed Hawa

Reputation: 1362

Simply ! == does not equal !==, as is not valid PHP code

Upvotes: 0

Jake Mac
Jake Mac

Reputation: 31

This will work:

(if($return_value !== false){
// do work
}

Comparisons:

  • == means same value
  • === means same value AND same type
  • ! == means not (same value)
  • !== means not (same value and same type)

SO:

  • 0 == false //is true
  • 0 === false //is false

Upvotes: 1

magnetronnie
magnetronnie

Reputation: 505

Use strict comparison with ===. See: https://www.php.net/manual/en/types.comparisons.php

if(1 === true) //returns FALSE

Upvotes: 1

Loïc
Loïc

Reputation: 11942

if ($return_value !== false) {

}

Using !== (or ===) instead of just != or == also tests the type of the value.

Upvotes: 6

Related Questions