Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse string as array in PHP

Tags:

arrays

php

I'm new to PHP and could not find a proper answer to this.

$whatever = "array('Test','Blah')";
echo $parsed[2]; //This will be "Blah"

I want to create a variable called $parsed which contains $whatever's value but as a valid array instead of a string.

I'm aware I can just create the array by removing the quotation marks around it like this:

$whatever = array('Test','Blah');

In the actual code I'm working on, though, this isn't a possibility. Also, in my actual code, the array is multidimensional, so something involving a character replacement would probably be impractical, however I'm not ruling it out if it's the best option.

So to sum it up, what's the best way to go about parsing a string as an array in PHP?

like image 858
UserIsCorrupt Avatar asked Aug 31 '12 09:08

UserIsCorrupt


1 Answers

Use the eval function: http://php.net/manual/en/function.eval.php.

$whatever = "array('Test','Blah')";
$parsed = eval("return " . $whatever . ";");
echo $parsed[1]; //This will be "Blah"

Be careful to check for the $whatever variable contents, because any PHP code can be executed.

like image 81
SirDarius Avatar answered Sep 24 '22 23:09

SirDarius