max max - 2 months ago 7x
PHP Question

How to convert string of array into array in php

I have a string like below:

$arrayString = "[Orange,Apple,Grape]";

How can I convert this into an Array?


I'm not a fan of str_replace replacing square brackets because they might be replaced in the array string, so let's trim them instead, and explode the list on the commas. Given your sample above, this will produce an array of strings.

$arrayString = "[Orange,Apple,Grape]";

print_r( explode(",", trim($arrayString, "][")) );


    [0] => Orange
    [1] => Apple
    [2] => Grape

Note: If you have escaped commas, then this won't work.