user2440987
user2440987

Reputation: 19

Convert array of comma-separated strings to a flat array of individual values

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
)

Upvotes: 0

Views: 102

Answers (3)

Tom
Tom

Reputation: 691

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
)

Upvotes: 0

Amal Murali
Amal Murali

Reputation: 76666

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);

Upvotes: 1

Matthew
Matthew

Reputation: 48284

$data = preg_split('/,\s*/', implode(',', $data));

Upvotes: 4

Related Questions