1

My string looks like:

[10,20,30]

I want to convert it to an array.

I've tried:

$myArray=explode(",",$myString);
print_r($myArray);

But this is returning:

Array ( [0] => [10 [1] => 20 [2] => 30] )

I need to get rid of the opening/closing brackets.

Can someone help?

1
  • What did you try to get rid of the opening/closing brackets? Commented Nov 11, 2013 at 0:07

2 Answers 2

8

An array of numbers in that particular format is valid JSON, so you can use PHP’s built-in function:

$myArray = json_decode($myString);
Sign up to request clarification or add additional context in comments.

Comments

-1

I think you can remove the square brackets first with str_replace function. Then you can simply do the rest. This will work I think.

$inputString = "[10,20,30]";
$processString = str_replace(array('[',']') ,'' , $inputString);
$outputArray = explode(',' , $processString);
var_dump($outputArray);

//output:
//array(3) { [0]=> string(2) "10" [1]=> string(2) "20" [2]=> string(2) "30" }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.