Armen Armen - 1 month ago 7
PHP Question

php alternative function for isset() to not return false if value is null

Is there any chanse to write alternative function for

isset()
function which will return true if key exists but its value is null

i know that there is php's array_key_exists for that but i was thinking to if it possible to somehow check it by arrays key reffarance somehow or someting like that

// check if array key set
function issetAK($param){
// some refarance check ?
}

$array = array('some_key'=>null);
issetAK( $array['some_key'] );


Douse any one experienced same or know solution for this ? or any idias ?

Answer

You can certainly hard-code the array into a global variable but that'd be unmaintainable. The other alternative would be a class:

<?php

class ArrayHelper {
    private $array;

    public function __construct(array $array) {
        $this->array = $array;
    }

    public function issetAK($param) {
        return array_key_exists($param, $this->array);
    }
}

$settings = new ArrayHelper(['width' => 200, 'height' => 125, 'ratio' => null]);
var_dump(
    $settings->issetAK('width'),
    $settings->issetAK('ratio'),
    $settings->issetAK('foobar')
);
bool(true)
bool(true)
bool(false)

Whether this is an enhancement over plain array_key_exists($param, $array) is another story. It probably depends on the specific use case and overall app design.