Search code examples
phpvariable-variables

PHP variable variables getting array value


I'm building a condition check where I'm passing in the variable and a value to check. In this case the variable is an array value, but I can't get it to return it correctly

//happens somewhere else
$specialFeature['option1']="on";
$specialFeature['option2']="on";
$specialFeature['option3']="off";

//what I'm trying to do
#query a db
$row = $result->fetch_array()
#results for purpose of demo
#$row['var'] = "specialFeature['option2']";
#$row['val'] = "on";
if($$row['var'] == $row['val']){
    //what i'm expecting
    echo "OK";
}

My issue is $$var is always null. What am I doing wrong? Is this possible?


Solution

  • I'm not sure if what I'm doing is "correct", but I got the result I was looking for by doing this:

    //happens somewhere else
    $specialFeature['option1']="on";
    $specialFeature['option2']="on";
    $specialFeature['option3']="off";
    
    //what I'm trying to do
    #query a db
    $row = $result->fetch_array()
    #results for purpose of demo
    #$row['var'] = "specialFeature['option2']";
    #$row['val'] = "on";
    
    $var = $row['var'];
    
    if (strpos($var,'[') !== false) {
        $varA = str_split($var,strpos($var,'['));
        $varA[1] = substr($varA[1],1,-1);
        if (strpos($varA[1],"'") !== false) {
            $varA[1] = substr($varA[1],1,-1);
        }
    }
    
    if(${$varA[0]}[$varA[1]] == $row['val']){
        //what i'm expecting
        echo "OK";
    }