7

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?

8
  • 1
    That should work, but would fail later for other reasons… how about a simple anonymous function…?
    – deceze
    Jul 5, 2017 at 13:11
  • 1
    Nesting functions!?! That's never sensible, and commonly misunderstood, as functions are never actually "nested"... but is your class namespaced, for example?
    – Mark Baker
    Jul 5, 2017 at 13:11
  • @deceze Not really because my understanding of Array_Map is that it looks for the function that exists outside the Map... Jul 5, 2017 at 13:21
  • Not sure what you mean by that, but it works just fine: stackoverflow.com/a/44927275/476
    – deceze
    Jul 5, 2017 at 13:22
  • @deceze No worries.... it's all sorted because of the answer below Jul 5, 2017 at 13:25

2 Answers 2

14

Do like this

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

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?

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.