phparraysmultidimensional-arraysplitexplode

Split the comma-separated string of a specified column in each row of a multidimensional array


If you have a multidimensional array, such as follows:

$array = array(
    'name' => 'user',
    'values' => 'one, two, three',
    'params' => array('three');    
);

How can you split 'values' key so it then becomes an array on its own?

i.e

$array = array(
    'name' => 'user',
    'values' => array('one', 'two', 'three'),
    'params' => array('three');    
);

Solution

  • If you wish to run this check on all the fields and not just the values one:

    foreach($array as &$value)
    {
        if (!is_array($value))
        {
            $value = explode(', ', $value);
        }   
    }
    unset($value);