Home » Php » php – how to know whether key exists in Json string

php – how to know whether key exists in Json string

Posted by: admin April 23, 2020 Leave a comment


Possible Duplicate:
How to check if an array element exists?

apologize if i am wrong,I am new to PHP, Is there any way to find out whether key exists in Json string after decoding using json_decode function in PHP.

$json = {"user_id":"51","password":"abc123fo"};


$json = {"password":"abc123fo"};
$mydata = json_decode($json,true);
user_id = $mydata['user_id'];

If json string doesn’t consist of user_id,it throws an exception like Undefined index user_id,so is there any way to check whether key exists in Json string,Please help me,I am using PHP 5.3 and Codeigniter 2.1 MVC Thanks in advance

How to&Answers:

IF you want to also check if the value is not null you can use isset

if( isset( $mydata['user_id'] ) ){
   // do something

i.e. the difference between array_key_exists and isset is that with

$json = {"user_id": null}

array_key_exists will return true whereas isset will return false


You can try array_key_exists.

It returns a boolean value, so you could search for it something like:

if(array_key_exists('user_id', $mydata)) {
    //key exists, do stuff