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?

Thanks.

Answers


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.


Need Your Help

How to insert ($x-$y) inside a bash printed string

linux bash shell command-line sh

I have this simple problem but I am very unfamiliar with bash syntax;

How to perform navigation in preRenderView listener method

jsf-2 navigation listener prerenderview

I'm starting from What can <f:metadata> and <f:viewParam> be used for?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.