mamelepera mamelepera - 1 year ago 83
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
check whether the variable called
exists or not?

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

Answer Source

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


$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 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download