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.

Appel Flap
  • 261
  • 3
  • 23

1 Answers1

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');
ka_lin
  • 9,329
  • 6
  • 35
  • 56
  • I've tried this but if the key doesn't exist, it will still trigger the undefined index error for me. – Appel Flap Mar 04 '19 at 15:33
  • Do some debug, sounds like there might be another issue. You can [test the method](http://sandbox.onlinephpfunctions.com/code/2a5e9b0c41938f6e7d0b6fd13322dc993737d036) by calling with an empty array or missing key to check – ka_lin Mar 04 '19 at 15:37
  • My bad, got it working now. Thank you. – Appel Flap Mar 04 '19 at 16:11