If you are annoyed by the behavior of isset() concerning null values, here is a handy function for you. its similar to array_key_exists but, its a lot more flexible and can check for multiple array keys across multiple arrays.
Not recursive!
Tested on php 8.1.6, linux
<?php
function is_set(string $var_name, array|null|string ... $args): bool {
$vars[$var_name] = null;
if (array_key_exists(0, $args)) {
if (is_array($args[0])) {
$vars[$var_name] = $args[0];
} elseif (is_string($args[0])) {
goto main;
}
unset($args[0]);
}
main:
if ($args) {
$args = array_reverse($args);
$cur_array = null;
array_walk($args, function ($value) use (&$cur_array, &$vars): void {
if (!is_string($value)) {
$cur_array = $value;
} else {
$vars[$value] = $cur_array;
}
});
}
foreach ($vars as $name => $array) {
if (!array_key_exists($name, $array??$GLOBALS)) return false;
}
return true;
}
$arr1 = range(0, 5);
$arr2 = [
'a' => 1,
'b' => 2,
'c' => 'hELLO wORLD!'
];
$gender = 'male';
$age = 12;
var_dump(is_set('age')); var_dump(is_set('age', null)); var_dump(is_set('age', $arr1)); var_dump(is_set('age', array())); var_dump(is_set('age', array('age' => 48))); var_dump(is_set('age', 'arr1', null, 'b', $arr2, 0, 3, 4, $arr1, 'gender')); var_dump(is_set('age', 'arr1', null, 'b', $arr2, 0, 3, 4, $arr1, 'gender', null)); $c=$d=$e=$a=2;
$arr = [1,4];
var_dump(is_set('a', 'c', null, 0, 1, $arr)); var_dump(is_set('a', 'c', null, 0, 4, $arr)); ?>
Note:
it won't work for variables declared locally inside a function;
however you can use it for checking if array keys exists inside a function