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?

2

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

+1, though I'd add that the asker might want a function for code reuse purposes, or any of a number of other valid reasons.
@user1153551: And? That's the same as array in the OP's question :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.