0

Is it possible to have just normal php code and not use eval() function in such case?

My eval code is following:

eval('$'.$var.'["'.$key.'"]="'.$value.'";');

And what I am doing is following:

function config_update($array, $var="result")
{ 
    global $result, $dbi;

    while (list($key,$value)=each($array))
    {
        if (is_array($value))
        { 
            config_update($value, $var.'["'.$key.'"]'); 
        } 
        else
        { 
            for ($i=0; $i<count($value);$i++)
            {
                if ($value == "{FROM_DB}")
                {
                    $query = $dbi->prepare("SELECT `value` FROM `".PRE."config` WHERE `key`=?;")->execute($key)->results();

                    if (!$query) 
                    {
                        trigger_error("There is no such key as `{$key}` in config database",E_USER_ERROR);
                        exit;
                    }
                    else
                        $value = str_replace("{FROM_DB}",$query[0]['value'],$value);
                }
                eval('$'.$var.'["'.$key.'"]="'.$value.'";');
                //$$var[$key] = $value; #smth like that..
            }
        }
    }
}

I basically need to update variable values with {FROM_DB} with values coming from DB.

2
  • "$$var[$key] = $value;" should work... isn't it? Commented Jan 20, 2013 at 23:19
  • Warning: Illegal string offset 'doc_root' in H:\xampp\htdocs\app_portable\boot.php on line 80 and not only doc_root such message loops for different configuration key names... Commented Jan 20, 2013 at 23:21

2 Answers 2

2

from the php manual on variable variables you should use {} when working with array based variable variables to avoid unknown behavior.

${$var}[$key] = $value

see Variable variables

Sign up to request clarification or add additional context in comments.

2 Comments

no problem, anything to reduce the use of eval out in the wild.
This is still ugly as it still uses "variable variables". I would recommend switching to the proper root ADT. (Very few languages support "variable variables"; and yet almost all computer languages support this same goal/operation.)
1

If you were to use:

$$var = array();
$$var[$key] = $value;

It would evaluate as:

$result[$key] = $value;

Assuming that $var = 'result'.

2 Comments

I know, but it does not work in my case for unknown reason and that is what I try to ask
Have you defined it as an array beforehand?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.