Search code examples
phpisset

PHP - Variable Safe Output


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.


Solution

  • 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');