Good day. The database has a params field in which arbitrary keys and values ​​are placed in the format: key => value, key2 => value2, ..., etc.

After receiving the params field in the $ params variable, I take the parameters as follows:

eval('$array=array(' . $params . ');'); extract($array); 

In other words: there is a string variable:

 $params = "key=>value, key2=>value2, key3=>value3"; //это не массив, это просто строка 

We need an algorithm for obtaining from this line the usual associative array.

Than eval is cool because it correctly converts even such a string to an array:

 $params = 'key=>"Lorem, ipsum; 22", key2=>[value2, value3, value4], key3=>value3'; 

Does this “algorithm” work, but am I confused by eval? Is my decision right? Is there a more elegant and correct way?

  • And why directly extract () is not used without eval ()? Something in the way? - cheops
  • @cheops arrow prevent ...) - Alexey Shimansky
  • because there the executing code creates an array - Dmitry Nail
  • I apologize, for some reason I thought that params, this is the resulting array, not a string. - cheops
  • @ E.Dio run through the loop, breaking the string k=>v through explode by the symbol => ..... and collect the array .... and then this array already make extract ...... because eval is dangerous and it is necessary to use it when there is no other choice at all - Alexey Shimansky

1 answer 1

Yes there is.

No "lines with parameters" in the database should even be close.
Values ​​are stored in the database, each in its own cell.

That is, instead of the line should be a TABLE. with those same key value pairs.

Receive so

 $array = $pdo->query("SELECT key, value FROM parameters")->fetchAll(PDO::FETCH_KEY_PAIR); 

Regarding the "coolness" of eval in the conversion of multidimensional arrays, I recommend to discover JSON.

  • Thank you, JSON is what you need! - E.Dio 2:29 pm