phparraysexplode

Explode each values of Array element


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
    )

)

Solution

  • 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.