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…? Commented 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? Commented 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... Commented Jul 5, 2017 at 13:21
  • Not sure what you mean by that, but it works just fine: stackoverflow.com/a/44927275/476 Commented Jul 5, 2017 at 13:22
  • @deceze No worries.... it's all sorted because of the answer below Commented Jul 5, 2017 at 13:25

2 Answers 2

16

Do like this

public function createCost(){
    $cost_example = array();
    $array_mapped = array_map(function ($array_item){
        return $array_item;
    }, $cost_example);
}
Sign up to request clarification or add additional context in comments.

Comments

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?

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.