2

I come from a JS world and have trouble understanding this piece of code:

function getCountryName($code, $codes){
  print_r($code);

  array_filter(
    $codes,
    function ($e) {
      if($e->cca2 == $code){
        print_r($e->name->common);
      }
    }
  );
}

The second line is for debug only and it prints given $code. But here: if($e->cca2 == $code){ $code seems to be undefined. How is it even possible? It works with $GLOBALS['code'] but I don't want to use globals. How come array_filter has no access to it's own scope?

3 Answers 3

3

$code is in getCountryName()’s scope. You then have a callback for array_filter(), which is an anonymous function and has its own scope. To access the variable, you need to use it, which will make the callback inherit the variable from its parent scope (the function):

function getCountryName($code, $codes){
print_r($code);
 array_filter(
    $codes,
    function ($e) use ($code) {
      if($e->cca2 == $code){
        print_r($e->name->common);
      }
    }
  );
}
Sign up to request clarification or add additional context in comments.

Comments

1

you need to use 'use'.

function getCountryName($code, $codes){
  print_r($code);

  array_filter(
    $codes,
    function ($e) use($code) {
      if($e->cca2 == $code){
        print_r($e->name->common);
      }
    }
  );
}

Comments

1

Because function() creates its own scope. If you want to pass a variable from the outside into the inner scope, you can use use:

array_filter(
  $codes,
  function ($e) use ($code) {
    if($e->cca2 == $code){
      print_r($e->name->common);
    }
  }
);

This way the use of the variable from the outside scope is explicit.

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.