Reputation: 535
I need help getting PHP to read an array name INSTEAD of the content in the array.
I am using PHP to parse a JSON response from an API call.
If the user inputs something incorrectly the JSON will respond with
array(1) { ["error"]=> ...
If the API request is successful the JSON that is returned is
array(2) { ["message"]=> ...
This would be easy if the API provided a ["success"]=true/false
, but instead it provides two completely different response on success or failure so I need PHP to be able to read the array names, instead of the array content.
I want to create an if statement in PHP based on the array name. I can pull the message from error or the message from message just fine, but I want PHP to check to see what the array title is called. I was thinking something like this...
$response = json_decode(file_get_contents($url), true);
if ($response[] == "error"){
echo "There was an error: ".$response["error"];
} else {
echo $response["message"];
}
Upvotes: 0
Views: 54
Reputation: 26153
If i understand correctly, you should test that the key is present in array
$response = json_decode(file_get_contents($url), true);
if(isset($response["error"])) { // errror }
if(isset($response["message"])) { // ok }
Upvotes: 2