Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP array_map callback function inside function

I have a function called createCost, and inside that function, I have an array_map that takes in an array and a function called checkDescription that's inside that createCost. Below is an example:

public function createCost{

  $cost_example = array();
  function checkDescription($array_item)
  {
    return $array_item;
  }

  $array_mapped = array_map('checkDescription', $cost_example);
}

When I run this I get a

array_map() expects parameter 1 to be a valid callback, function 'checkDescription' not found or invalid function name

Which to my understanding is that it looked for the function checkDescription outside that createCost but how can I call checkDescription from inside?

like image 919
Greg Sithole Avatar asked Dec 07 '22 17:12

Greg Sithole


2 Answers

Do like this

public function createCost(){
    $cost_example = array();
    $array_mapped = array_map(function ($array_item){
        return $array_item;
    }, $cost_example);
}
like image 162
Bibhudatta Sahoo Avatar answered Dec 10 '22 23:12

Bibhudatta Sahoo


Why not assign the function to a variable?

public function createCost{

  $cost_example = array();
  $checkDescription = function ($array_item) {
                          return $array_item;
                      }

  $array_mapped = array_map($checkDescription, $cost_example);
}

Isn't this more readable too?

like image 23
Gruber Avatar answered Dec 10 '22 22:12

Gruber