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;}
        }
}
3
  • 1
    Does this answer your question? php function variable scope Commented Mar 23, 2020 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. Commented Mar 23, 2020 at 19:40
  • Thanks, it helped. Commented Mar 23, 2020 at 19:58

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.