ngplayground
ngplayground

Reputation: 21617

php if and isset and if variable is not set and doesnt exist

Possibly a strange one that I hope can be done in one line.

I have to have an IF statement that will checks two things.

The reason being that when the first variable equals staff then the 'address1' variable doesn't exist.

I did have the following but when I log in as staff it still checks for the address1

if((isset($loggedInfo['status'])=="client")&&(!$loggedInfo['address1'])){
  //Do something
}

Upvotes: 0

Views: 4281

Answers (3)

Morgan Wilde
Morgan Wilde

Reputation: 17303

Well you just can't compare the return value of isset() with the string "client", because it will never equal that. To quote http://php.net/manual/en/function.isset.php its return values are "TRUE if var exists and has value other than NULL, FALSE otherwise".

First check if it is set

if ((isset($loggedInfo['status']) === true) && ($loggedInfo['status'] === "client") && (empty($loggedInfo['address1']) === true)) {
    // Do something
}

Key take away from this should be to look up return values for every function you use, like empty(), in the manual http://www.php.net/manual/en/function.empty.php. This will save you a lot of headaches in the future.

Upvotes: 1

Tomas Ramirez Sarduy
Tomas Ramirez Sarduy

Reputation: 17471

if((isset($loggedInfo['status']) && $loggedInfo['status']=="client") &&(empty($loggedInfo['address1'])){
  //Do something
}

isset() returns TRUE if the given variable is defined in the current scope with a non-null value.

empty() returns TRUE if the given variable is not defined in the current scope, or if it is defined with a value that is considered "empty". These values are:

NULL    // NULL value
0       // Integer/float zero
''      // Empty string
'0'     // String '0'
FALSE   // Boolean FALSE
array() // empty array

Depending PHP version, an object with no properties may also be considered empty.

Upvotes: 1

Maxim Krizhanovsky
Maxim Krizhanovsky

Reputation: 26699

isset returs true or false. you have to do separate check for the actual value

if(
 isset($loggedInfo['status']) && $loggedInfo['status']=="client" &&
 isset($loggedInfo['address1']) && trim($loggedInfo['address1']) != ''
)
{
  //Do something
}

Upvotes: 3

Related Questions