Matt
Matt

Reputation: 22911

Adding a key & value to all arrays within an array

I would like to take this:

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

Run a function and have the result be:

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'm looping through with a foreach loop. Is there a better way? The key/value can are always going to be the same.

Thanks! Matt Mueller

Upvotes: 2

Views: 93

Answers (2)

RiaD
RiaD

Reputation: 47620

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

Upvotes: 1

Paige Ruten
Paige Ruten

Reputation: 176665

I don't think a better way exists. A foreach loop isn't a bad way to do it. Short and simple:

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

Upvotes: 2

Related Questions