5

I have an array like :

Array
(
   [2] => 2,6
   [3] => 1
   [4] => 14
   [5] => 10
   [6] => 8
)

I want to explode each element of an array and return a new array using array_map, so that I can avoid using loop, and creating extra function to call back.

O/p should be like :

  Array
(
[2] => Array
    (
        [0] => 2
        [1] => 6
    )

[3] => Array
    (
        [0] => 1
    )

[4] => Array
    (
        [0] => 14
    )

[5] => Array
    (
        [0] => 10
    )

[6] => Array
    (
        [0] => 8
    )

)
Alok Jha
  • 562
  • 7
  • 22

4 Answers4

8

You can use

$result = array_map(function($val) {
    return explode(',', $val);
}, $input);

Which will result in

Array
(
    [2] => Array
        (
            [0] => 2
            [1] => 6
        )

    [3] => Array
        (
            [0] => 1
        )

    [4] => Array
        (
            [0] => 14
        )

    [5] => Array
        (
            [0] => 10
        )

    [6] => Array
        (
            [0] => 8
        )

)

This will work on PHP >= 5.3 with support for anonymous functions.

Philipp Palmtag
  • 1,310
  • 2
  • 16
  • 18
4

You can also do

$result = array_map('str_getcsv', $input);

This will also result in

Array
(
    [2] => Array
        (
            [0] => 2
            [1] => 6
        )

    [3] => Array
        (
            [0] => 1
        )

    [4] => Array
        (
            [0] => 14
        )

    [5] => Array
        (
            [0] => 10
        )

    [6] => Array
        (
            [0] => 8
        )

)
Arul Kumaran
  • 983
  • 7
  • 23
2

Try following code

$newArr = array_map(function($val, $key){
    return explode(",", $val);
}, $arr);
Mohit Tanwani
  • 6,608
  • 2
  • 14
  • 32
0

$data = array(2 => '2,6',3 => '1',4 => '14',5 => '10',6 => '8');

foreach($data as $key => $val) {
    $new = explode(',',$val);
    $data[$key] = $new;
}
$output = $data;

echo '<pre>';
print_r($output);
Philipp Palmtag
  • 1,310
  • 2
  • 16
  • 18
Dilip Kale
  • 71
  • 7
  • I dont want any extra loops, as we have array_map – Alok Jha Aug 29 '16 at 10:29
  • While this code snippet may solve the question, [including an explanation](//meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, as this reduces the readability of both the code and the explanations! – Blue Aug 29 '16 at 19:41