0

I have an array as follows:

$array['a'] = 'Red';
$array['b'] = 'Green';
$array['c'] = 'Blue';

I want to convert it to:

$array['a'][1] = 'Red';
$array['b'][1] = 'Green';
$array['c'][1] = 'Blue';

Is that possible with an existing PHP function or do I need to write my own function?

H. Ferrence
  • 7,906
  • 31
  • 98
  • 161
  • http://stackoverflow.com/questions/20728171/convert-1d-array-to-2d-array-and-join-php http://stackoverflow.com/questions/18658475/converting-1d-array-to-a-2d-array-with-count-of-elements – JimmyBanks Mar 25 '14 at 16:12
  • maybe: array_walk($array, function(&$v, $k){ $v = array(1 => $v) }) – Mahakala Mar 25 '14 at 16:13

1 Answers1

4

No, there is no built-in function that can achieve this. However, this is pretty straight-forward with a foreach loop, so I don't see why you need a function:

$result = array();

foreach ($array as $key => $value) {
    $result[$key][1] = $value;
}

print_r($result);

If you want a more functional approach, you could use array_walk():

// walks through the original $array and adds a new dimension
array_walk($array, function(&$v, $k){ 
    $v = array(1 => $v); 
});

Although, a normal foreach would be more straight-forward and readable.

Amal Murali
  • 75,622
  • 18
  • 128
  • 150