jbrahy jbrahy - 4 months ago 11
PHP Question

Create array of arrays by assigning keys while creating sub arrays

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);

Answer

The alternative solution using array_map function:

$desired_array = array_map(function($v) use($key){ return [$key => $v]; }, $values);