Search code examples
phpif-statementvariablesvariable-names

Php: check if variable value exist as a variable || make variable value a variable


Is it possible to check if a variable exist using a variable value? Like

//some variables:
$variable_a;
$variable_b;
$variable_c;
$variable_d;

$variable = '$variable_b';
     if (the content $variable which is '$variable_b' exists == true){
    
}

or how to make a variable value into a variable? Like

$variable = 'variable_name'; ...some code to make 'variable_name' a variable


Solution

  • You can use variable variables in PHP, and then check if such a variable has a value. For instance:

    $variableA = 'Hello';
    $variableB = 'variableA';
    echo ${$variableB};
    

    returns Hello on your screen. You can also check if $variableA has a value by doing:

    if (isset(${$variableB})) {
        ....
    }
    

    Note that in your question you have variables that have no value, they are not set. The whole purpose of variables is to have a value, hence their name, so your variables are some kind of zombies, not really alive, not really dead. They are not set, so isset() will return false.