Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct PHP code to check if a variable exists

This code is part of a websocket server:

$msgArray = json_decode($msg);
if ($msgArray->sciID) {
  echo "Has sciID";
}

It will either be receiving a json string like {"sciID":67812343} or a completely different json string with no sciID such as {"something":"else"}.

When the server receives the later, it echos out: Notice: Undefined property: stdClass::$sciID in /path/to/file.php on line 10

What is the correct code to check if $msgArray->sciID exists?

like image 625
JJJollyjim Avatar asked May 01 '11 23:05

JJJollyjim


People also ask

What is $_ GET in PHP?

PHP $_GET is a PHP super global variable which is used to collect form data after submitting an HTML form with method="get". $_GET can also collect data sent in the URL. Assume we have an HTML page that contains a hyperlink with parameters: <html> <body>

How check variable true or false in PHP?

The is_bool() function checks whether a variable is a boolean or not. This function returns true (1) if the variable is a boolean, otherwise it returns false/nothing.

Which function is used to check whether a variable is already set or not?

Determine if a variable is considered set, this means if a variable is declared and is different than null . If a variable has been unset with the unset() function, it is no longer considered to be set. isset() will return false when checking a variable that has been assigned to null .

What does ?: Mean in PHP?

The Scope Resolution Operator (also called Paamayim Nekudotayim) or in simpler terms, the double colon, is a token that allows access to static, constant, and overridden properties or methods of a class.


Video Answer


3 Answers

Use isset as a general purpose check (you could also use property_exists since you're dealing with an object):

if (isset($msgArray->sciID)) {
    echo "Has sciID";
}
like image 79
Ross Avatar answered Oct 30 '22 13:10

Ross


property_exists()?

like image 35
Oliver Charlesworth Avatar answered Oct 30 '22 13:10

Oliver Charlesworth


In case isset() or property_exists() doesn't work, we can use array_key_exists()

if (array_key_exists("key", $array)) {
    echo "Has key";
}
like image 24
Petr Hurtak Avatar answered Oct 30 '22 14:10

Petr Hurtak