0

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

1 Answer 1

2

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 }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.