2

I could write it out like this.

 $key = "sid";
 $values = array(1,2,3);
 $desired_array = array();

 foreach($values as $value){
     $desired_array[] = array($key => $value);
 }

 print_r($desired_array);

The output would look like this.

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

    [1] => Array
        (
            [sid] => 2
        )

    [2] => Array
        (
            [sid] => 3
        )     
)

I was hoping there was a fancy php array function I didn't know about that could create that for me so keep my code terser.

Here's the completed solution, maybe it's not much shorter but I'm always happy when I get to use array_map.

 $key = "sid";
 $values = array(1,2,3);
 $desired_array = array_map(function($value) use($key){
    return array($key=>$value);
 },$values);

2 Answers 2

2

The alternative solution using array_map function:

$desired_array = array_map(function($v) use($key){ return [$key => $v]; }, $values);
Sign up to request clarification or add additional context in comments.

1 Comment

The use($key) is exactly what I needed to make array_map work the way I needed. Thanks!
2

You may be looking for array_map.

It would work something like this:

$array = [1, 2, 3];
$desired = array_map(function ($item) {return ['sid' => $item];}, $array);

I believe this link should work for a demonstration as well.

2 Comments

Thanks, but it was the use() that I was missing when I initially tried array_map. It was in RomanPerekhrest's answer.
Yep, if you want a variable key his is the better answer.

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.