Elo97234c Elo97234c - 1 year ago 219
JSON Question

PHP check if array key exist

I have a array and within that array i have more elements. I want to check if a specific element exist

$jsondata = file_get_contents('php://input');
$jsonobj = json_decode($jsondata, true);


Possibility 1



$jsonobj=Array(
[user] => Array
(
[userId] => 1501148600220
[locale] => en-US
// no TOKEN
)
);


Possibility 2



$jsonobj=Array(
[user] => Array
(
[userId] => 1501148600220
[locale] => en-US
[token] => 12345 // TOKEN exist
)
);


The follwing is a decoded JSON.

The Received JSON sometimes might and might not contain the element 'token'.

I want to check if the $jsonobj has the element 'token'

if (array_key_exists('token', $jsonobj)) {
echo "Element is in the array";
}


How do i check this according to the structure of my array?

UPDATE



Sometimes, the jsonobj might not contain anything. It could be empty. If it is empty i get an error

PHP Warning: array_key_exists() expects parameter 2 to be array

Answer Source

You just need to pass the index 'user' in the multidimensional $jsonobj array

Like this

if (array_key_exists('token', $jsonobj['user'])) {
  echo "Element is in the array";
 }

Modified:-

$jsonobj=json_decode($jsonobj,true);
if(!empty($jsonobj['user'])&&is_array($jsonobj['user']))
{
    if (array_key_exists('token', $jsonobj['user'])) {
        echo "Element is in the array";
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download