max max - 1 year ago 61
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?

Answer Source

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, "][")) );

Results:

Array
(
    [0] => Orange
    [1] => Apple
    [2] => Grape
)

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download