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
We can have duplicate keys in a JSON object, and it would still be valid.
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".
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.
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 }
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