Are there any way to check exitency of an array key inside the function

114 Views Asked by At

I have a project that I need to echo $variable['key'];

Some times $variable['key'] is not exist. And Those variables creates errors when I echo $variable['key']; directly.

My current method is

echo (isset($variable['key'])) ? $variable['key'] : '';

And this is not very efficient way of doing that. I do not want to write all keys two times.

I need a function. Basically That checks the $varible['key']; inside the function and returns the value of it.

function get_ifisset(&$var = null){
if(isset($var)){ return $var; }
}

echo get_ifisset($vars['key']);

but because of $variable['key'] is not exist I can not send them inside to the function

This kind of usage throws error which is "undefined key".

Also following function is an another approach that I dont like.

function get_ifisset($var, $key){
if(array_key_exists($key, $GLOBALS[$var])){ return $GLOBALS[$var][$key]; }
}

I would like to learn Are there any way to check exitency of an array key inside the function.

property_exists(); array_key_exists(); isset();

2

There are 2 best solutions below

2
On

modified @Justinas function:

public function getValue($array, $key, $default = '') {
    if(!is_array($key)) {
        return isset($array[$key]) ? $array[$key] : $default;
    }
    $arr = & $array;
    foreach($key as $subkey) {
        if(!isset($arr[$subkey])) {
            return $default;
        }
        $arr = & $arr[$subkey];
    }
    return $arr;
}

so you can use it on multidimensional arrays

getValue($array, "key");

getValue($array, Array("key", "subkey", "subsubkey"));
3
On

You can pass array, key and default value to function:

public function getValue($array, $key, $default = '') {
    return isset($array[$key]) ? $array[$key] : $default;
}

$this->getValue($variable, 'key');

Also, from my experience function get_ifisset(&$var) does not throw any error (I have not set it default to null).