PHP error. Why is "variable undefined" inside array_map?

Kanishka Panamaldeniya picture Kanishka Panamaldeniya · Jan 17, 2012 · Viewed 22.6k times · Source

I am using array_map function in my php application. I defined the array_map function like this.

$ratingID =  $this->db->insert_id();

    $rated_item_array = array_map(function ($a) {
        return $a + array('RatingID' => $ratingID);
    }, $rated_item_array);  

Php notice comes

A PHP Error was encountered

Severity: Notice

Message: Undefined variable: ratingID

When i print the $ratingID . i prints the value correctly , so $ratingID is defined. Why it is undfined in array_map function? My $rated_item_array is

Array
(
    [0] => Array
        (
            [RatingFactorPreferenceID] => 1,
            [PreferenceID] => 45,
            [RatedValue] => 1,
            [CreatedOn] => 1326790338,
            [CreatedBy] => 25
        )

    [1] => Array
        (
            [RatingFactorPreferenceID] => 2,
            [PreferenceID] => 45,
            [RatedValue] => 1,
            [CreatedOn] => 1326790338,
            [CreatedBy] => 25
        )

    [2] => Array
        (
            [RatingFactorPreferenceID] => 3,
            [PreferenceID] => 45,
            [RatedValue] => 1,
            [CreatedOn] => 1326790338,
            [CreatedBy] => 25
        )
)

Answer

xdazz picture xdazz · Jan 17, 2012
$rated_item_array = array_map(
  function ($a) use ($ratingID){ 
    return $a + array('RatingID' => $ratingID ); 
  }, 
  $rated_item_array
);