1

I have an array that I pull that looks like this:

[157966745,275000353,43192565,305328212]...

How do I go about taking that "string" and converting it to a PHP array which I can then manipulate.

3
  • You have an array which you want to convert to... an array also? Commented Jun 1, 2011 at 20:18
  • PHP doesn't accept that format as an array, so yes. Commented Jun 1, 2011 at 20:21
  • Where does this come from? Is it really a string? If so, you should rename your question. Commented Jun 1, 2011 at 20:23

5 Answers 5

10

This looks like JSON, so you can use json_decode:

$str = "[157966745,275000353,43192565,305328212]";
$data = json_decode($str);
Sign up to request clarification or add additional context in comments.

2 Comments

@Switz: You're welcome. Note that this will only work if you have numeric values. Strings values would have to be enclosed in double quotes.
In this context, json_decode() will produce an array of integers whereas explode() will create an array of strings.
2
$s = "[157966745,275000353,43192565,305328212]";

$matches;
preg_match_all("/\d+/", $s, $matches);

print_r($matches);

Comments

2

With exact that code...

$string='[157966745,275000353,43192565,305328212]';
$newString=str_replace(array('[', ']'), '', $string); // remove the brackets
$createArray=explode(',', $newString); // explode the commas to create an array

print_r($createArray);

Comments

0

PHP explode is built just for this.

$result = explode(',', $input)

2 Comments

What about the square brackets?
...the first and last elements get braces included as "bonus" characters.
0

The answer by @Felix Kling is much more appropriate given the context of the question.

$new_string = preg_replace('/([\[|\]])/', '', $strarr);
$new_array = explode(',', $new_string);`

1 Comment

There is no benefit to using capture groups when you are replacing the whole string. Character classes must not contain pipes with the intention to delimit characters inside the expression.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.