Mostafa Elkady
Mostafa Elkady

Reputation: 5791

Unexpected PHP behaviour in isset and empty

array(4) { ["id"]=>  int(0) ["pass"]=>  string(0) "" ["log_in"]=>  string(3) "no"  } 

The problem in id when using isset it return true because it's 0. When using empty I think it's doing the same. What is the best function to know whether it's set or not?

Upvotes: 1

Views: 166

Answers (5)

aefxx
aefxx

Reputation: 25249

Take a look at this chart on the PHP site.

Upvotes: 1

Sarfraz
Sarfraz

Reputation: 382696

empty returns false for these:

  • "" (an empty string)
  • 0 (0 as an integer)
  • "0" (0 as a string)
  • NULL
  • FALSE
  • array() (an empty array)
  • var $var (a variable declared, but without a value in a class)

You need to use isset instead to check if it is there.

See this article on empty vs isset for more info.

Upvotes: 5

ntan
ntan

Reputation: 2205

if id is a database id is positive integer

so if($id>0) is one simple solution

OR

preg_match('#^[0-9]*$#', $id)

another

Upvotes: 1

Steve
Steve

Reputation: 5853

if($array['id'] === 0) {
  true
} ?

Upvotes: 2

Gaurav Sharma
Gaurav Sharma

Reputation: 2848

a simple if condition will do for you

if(id)
{
}

try it if it works.

Upvotes: 1

Related Questions