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?

Greg Sithole
  • 145
  • 1
  • 2
  • 11
  • 1
    That *should* work, but would fail later for other reasons… how about a simple anonymous function…? – deceze Jul 05 '17 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 05 '17 at 13:11
  • @deceze Not really because my understanding of Array_Map is that it looks for the function that exists outside the Map... – Greg Sithole Jul 05 '17 at 13:21
  • Not sure what you mean by that, but it works just fine: https://stackoverflow.com/a/44927275/476 – deceze Jul 05 '17 at 13:22
  • @deceze No worries.... it's all sorted because of the answer below – Greg Sithole Jul 05 '17 at 13:25
  • @MarkBaker I'm using Laravel so my `createCost` is actually a Route Function and I needed to use a array_map to process that Route's data... and with each route, I'm processing the array of arrays with array_map... The answer below sorted my issue – Greg Sithole Jul 05 '17 at 13:27
  • This is a valid question and actually a common issue (the views prove it) as such a scenario is not shown in the documentation (as it is assumed that a function should not be nested). – Bobby Axe Feb 08 '20 at 09:09
  • Because there is no samle data / context / expected result, I find this question Unclear. – mickmackusa Mar 08 '20 at 11:22

2 Answers2

14

Do like this

public function createCost(){
    $cost_example = array();
    $array_mapped = array_map(function ($array_item){
        return $array_item;
    }, $cost_example);
}
Bibhudatta Sahoo
  • 4,808
  • 2
  • 27
  • 51
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?

Gruber
  • 2,196
  • 5
  • 28
  • 50