mamelepera mamelepera - 4 months ago 7
PHP Question

Check whether variable with the name of array value is set or not

So I have this array:

$myArray = array('myVar', 'myVar75', 'myVar666');


How do I
isset
check whether the variable called
$myVar
,
$myVar75
,
$myVar666
exists or not?

What is the most sensible way of passing the array's value into the
isset()
function as a variable name to check?

Answer

Just use variable variables to test each element with a simple foreach loop:

Example:

$myVar666 = 1; // for example's sake
$myArray = array('myVar', 'myVar75', 'myVar666');
foreach($myArray as $element) {
    if(isset(${$element})) {
        echo $element, ' is already set';
    } else {
        echo $element, ' is not yet set';
        // if not set, do something here
    }
}

Should yield something like this:

$myVar is not yet set 
$myVar75 is not yet set 
$myVar666 is already set