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?
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>
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.
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 .
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.
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";
}
property_exists()
?
In case isset()
or property_exists()
doesn't work, we can use array_key_exists()
if (array_key_exists("key", $array)) {
echo "Has key";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With