Convert PHP string with an array statement into a real array
I got a string var named: $taxonomy_str
For example, echo $taxonomy_str will display:
array('relation' => 'AND', array('taxonomy' => category, 'field' => 'id', 'terms' => array( 41, 42 ), 'operator' => 'IN'), array('taxonomy' => geography, 'field' => 'id', 'terms' => array( 20, 29 ), 'operator' => 'IN') )
I need a way to convert this string with an array statement into a real array, how can I achieve this using PHP?
A somewhat trivial thing to do is simply eval:
eval('$foo = ' . $taxonomy_str . ';'); // $foo now contains the outer array
(from the comments) maybe better form:
$foo = eval('return ' . $taxonomy_str . ';');
This literally executes $taxonomy_str as if it were source, so any valid PHP provided as input will run. There's a certain level of danger here if you were to say, take $taxonomy_str as input from a user.
You can use eval(), but it's really not safe if you take your string from the user input.