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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With