Search code examples
phparraysarray-map

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?


Solution

  • Do like this

    public function createCost(){
        $cost_example = array();
        $array_mapped = array_map(function ($array_item){
            return $array_item;
        }, $cost_example);
    }