Megandi Megandi - 6 months ago 10
JSON Question

How to input JSON data with dynamic data array?

Person 1 inputs data and the data array looks like this :

{
"type": "1",
"name": "John",
"phone":"898171"
}


Person 2 has not set the phone and the data array looks like this :

{
"type": "1",
"name": "Lisa"
} // only write 2 array...


I have source code in my controller like this :

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

if(!$data['phone']->iSEmpty){
echo "you haven't set the phone number!"
}


But this is not working. I get the following error when Person 2 inputs the data -


"Undefined index: phone"

Answer

The problem is you are trying to check a value of an undefined key.

You could use array_key_exists to check it:

if (!array_key_exists('phone', $data)) {
    echo "you haven't set the phone number!";
}