PHP array_map callback function inside function
Asked Answered
S

2

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?

Slighting answered 5/7, 2017 at 13:9 Comment(8)
That should work, but would fail later for other reasons… how about a simple anonymous function…?Functionary
Nesting functions!?! That's never sensible, and commonly misunderstood, as functions are never actually "nested"... but is your class namespaced, for example?Stirps
@Functionary Not really because my understanding of Array_Map is that it looks for the function that exists outside the Map...Slighting
Not sure what you mean by that, but it works just fine: https://mcmap.net/q/1408571/-php-array_map-callback-function-inside-functionFunctionary
@Functionary No worries.... it's all sorted because of the answer belowSlighting
@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 issueSlighting
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).Tanning
Because there is no samle data / context / expected result, I find this question Unclear.Sappanwood
F
15

Do like this

public function createCost(){
    $cost_example = array();
    $array_mapped = array_map(function ($array_item){
        return $array_item;
    }, $cost_example);
}
Fantan answered 5/7, 2017 at 13:11 Comment(0)
B
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?

Boiler answered 9/1, 2020 at 7:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.