Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to know whether key exists in Json string [duplicate]

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"}; 

Brief:

$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

like image 393
Nishanth Avatar asked Apr 16 '12 14:04

Nishanth


People also ask

Can JSON contain duplicate keys?

We can have duplicate keys in a JSON object, and it would still be valid.

Can JSON have multiple keys with same name?

There is no "error" if you use more than one key with the same name, but in JSON, the last key with the same name is the one that is going to be used. In your case, the key "name" would be better to contain an array as it's value, instead of having a number of keys "name".

Are keys in JSON always strings?

In JSON, the “keys” must always be strings. Each of these pairs is conventionally referred to as a “property”. In Python, "objects" are analogous to the dict type. An important difference, however, is that while Python dictionaries may use anything hashable as a key, in JSON all the keys must be strings.


2 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

like image 93
scibuff Avatar answered Sep 24 '22 07:09

scibuff


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 } 
like image 20
Jordan Avatar answered Sep 26 '22 07:09

Jordan