0

I'm fetching information from a unofficial API. This API is very large and sometimes doesn't have all elements in it. I'm trying to display values from this API on my site without any errors.

What I've done is check the JSON values like so, to prevent errors:

echo (isset($json['item'])) ? $json['item'] : '';

Works, but it looks very unorganized. I've thought about creating a function to handle safe output, like so:

public function safeoutput($input, $fallback = '') {
    if(isset($input)) {
        return $input;
    }

    if(empty($input) || !isset($input)) {
        return $fallback;
    }
}

and then doing:

echo $engine->safeoutput($json['item'], 'Unavailable');

That unfortuanlly still outputs the Undefined variable error.

I was wondering if there's a better way to handle such information like I showed in the example.

1
  • 3
    PHP7 knows easy syntax: $json['item'] ?? 'my default value'. Commented Mar 4, 2019 at 15:18

1 Answer 1

1

Problem is that the key might not be set, so you would have to check it:

public function safeoutput($input, $key, $fallback = '') {
    if(isset($input[$key])) {
        return $input;
    }

    if(empty($input[$key]) || !isset($input[$key])) {
        return $fallback;
    }
}

Or you can have a shorter version:

public function safeoutput($input, $key, $fallback = '') {
    if(array_key_exists($key, $input) && !empty($input[$key])){
        return $input[$key];
    }
    return $fallback;
}

And call the method with the array and the key:

echo $engine->safeoutput($json, 'item', 'Unavailable');
Sign up to request clarification or add additional context in comments.

3 Comments

I've tried this but if the key doesn't exist, it will still trigger the undefined index error for me.
Do some debug, sounds like there might be another issue. You can test the method by calling with an empty array or missing key to check
My bad, got it working now. Thank you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.