0

I need to change an array of comma-delimited integers into an array of individual numbers.

Sample input:

[
    '1,24,5',
    '4',
    '88, 12, 19, 6'
]

Desired result:

Array
(
   [0] => 1
   [1] => 24
   [2] => 5
   [3] => 4
   [4] => 88
   [5] => 12
   [6] => 19
   [7] => 6
)
1
  • 2
    looping over the original array, exploding each entry and merging the results all together into a new array (possibly with a trim for good measure) Commented Sep 26, 2013 at 19:54

3 Answers 3

4
$data = preg_split('/,\s*/', implode(',', $data));
Sign up to request clarification or add additional context in comments.

Comments

1

You can use the following solution:

$result = array();
foreach($inputArray as $value) {
    $result = array_merge($result, explode(',', $value));
}

Demo!


Original answer:

$arr = array('1,24,5', 4, '88, 12, 19, 6');
$result = array();

foreach ($arr as $value) {
    if(strpos($value, ',') !== FALSE) {
        $result = array_merge($result, explode(',', $value));
        $result = array_map('trim', $result); // trim whitespace
    }
    else {
        $result[] = trim($value);
    }
}

print_r($result);

Comments

0
Array(
  '1,24,5',
  '4',
  '88,12,19,6'
);


$new_arr = explode(',',implode(',',array_values($old_arr)));


Array
(
  [0] => 1
  [1] => 24
  [2] => 5
  [3] => 4
  [4] => 88
  [5] => 12
  [6] => 19
  [7] => 6
)

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.