0

I need to check whether selected city ( $_GET['city'] ) behaves in $cities array or not. Right now i'm getting errors "Undefined variable: cities" and "Invalid argument supplied for foreach()". If i check $cities with is_array it returns true. How can i fix my code?

$cities = array ("London" => "name/name2/name3", 
"Paris" => "name/name3/name4", 
"Moscow" => "name/name5/name6", 
"Paraguay" => "name/name4/name5");



function CityIsCorrect() {                                                                  //IN WORK
        if (empty($_GET['city'])) {return false;}
        foreach ($cities as $citycheck){
            if(($_GET['city'])==$citycheck) {return true;}
            else {return false;}
        }
}
dac0n
  • 29
  • 1
  • 7
  • 1
    Does this answer your question? [php function variable scope](https://stackoverflow.com/questions/5912036/php-function-variable-scope) – kip Mar 23 '20 at 19:37
  • 1
    Hi, it is related to scope, in PHP a function block code doesn't know/have access to the variables outside its block, so `$cities` is undefined inside `CityIsCorrect()` function. You would need to add a parameter `$cities` to the function and pass the variable `$cities` when calling the function. – Ermac Mar 23 '20 at 19:40
  • Thanks, it helped. – dac0n Mar 23 '20 at 19:58

1 Answers1

0

To directly answer your question – add this line to your function:

global $cities

By default, all variables within a function are "local." If you want to refer to a global function (a variable declared outside of any function-block), you must use global.

Mike Robinson
  • 8,490
  • 5
  • 28
  • 41