55

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

Community
  • 1
  • 1
Nishanth
  • 581
  • 1
  • 4
  • 3

2 Answers2

95

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

scibuff
  • 13,377
  • 2
  • 27
  • 30
  • 'array_Key_exists' not working it is throwing error. array_key_exists(): Argument #2 ($array) must be of type array, stdClass given – ajay chawla Feb 28 '22 at 07:41
  • 2
    it's `array_key_exists` not `array_Key_exists` (lowercase 'k') ... but the error says your second argument is not an array but an stdClass, i.e. you are most likely not passing `true` as the second argument to your `json_decode` function – scibuff Feb 28 '22 at 11:56
  • Oh, I see. thanks – ajay chawla Mar 01 '22 at 06:25
39

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
}
Jordan
  • 31,971
  • 6
  • 56
  • 67