I am working in php where I need to add a static value at each index of existing single dimensional array so that after adding it will become multidimensional array.
Existing single dimensional array:
[checklists] => Array
(
[0] => 20
[1] => 50
[2] => 35
[3] => 23
[4] => 24
[5] => 21
[6] => 22
[7] => 27
[8] => 25
)
Static value to be inserted 90
After insertion array will look like this:
[checklists] => Array
(
[0] => Array(90,20)
[1] => Array(90,50)
[2] => Array(90,35)
[3] => Array(90,23)
[4] => Array(90,24)
[5] => Array(90,21)
[6] => Array(90,22)
[7] => Array(90,27)
[8] => Array(90,25)
)
I want to know is there any php builtin function through which i can achieve this or should i use loop?
You can use array_map, $static is your 90, $array is your array.
$array['checklists'] = array_map(function($v) use($static){
return [$static, $v];
}, $array['checklists']);
Demo: https://3v4l.org/3ugLR
Here we are using array_map
to achieve the desired output.
Solution 1:
$staticValue=90;
$array["checklists"]= array_map(function($value) use ($staticValue){
return array($staticValue,$value);
}, $array["checklists"]);
print_r($array);
Solution 2: try this simplest one
$staticValue=90;
foreach($array as &$value)
{
$value=array($staticValue,$value);
}
print_r($array);
To modify an array, array_walk
can be used:
array_walk($array['checklists'], 'addStatic');
function addStatic(&$v) {
$v = [90, $v];
}
More easy way you can do this.
$array = array();
$array['checklist'][] = array(90, 20);
$array['checklist'][] = array(90, 50);