10, "left"=>10), array("top"=>50, "lef...">

Adding key and value to all arrays in an array

I would like to accept this:

$arr = array(
   array("top"=>10, "left"=>10),
   array("top"=>50, "left"=>30),
   array("top"=>60, "left"=>70)
);

      

Run the function and get:

array(
   array("top"=>10, "left"=>10, "width"=>400),
   array("top"=>50, "left"=>30, "width"=>400),
   array("top"=>60, "left"=>70, "width"=>400)
);

      

Right now I am iterating over the foreach loop. Is there a better way? The key / value value will always be the same.

Thank! Matt Mueller

+2


source to share


2 answers


I don't think there is a better way. The foreach loop is a good way to do this. In short and simple:



foreach ($arr as &$val) {
    $val['width'] = 400;
}

      

+2


source


array_map(function($x){
    $x['width'] = 400;
    return $x;
}, $arr);

      



+1


source







All Articles