Reputation: 7153
I am new-ish to PHP have read the PHP Variable scope docs and other Stackoverflow threads and can't get my head around why setting a global var inside a foreach loop doesn't work:
if (isset($regionsArr) && $page == 'regions') {
$param = htmlspecialchars($_GET["region"]);
foreach ($regionsArr as $item) {
if ($item['region'] == $param) {
global $curRegion;
$curRegion = $item;
echo $GLOBALS["curRegion"]["name"]; // works
} else {
$curRegion = null;
}
}
}
if (isset($GLOBALS["curRegion"])) {
echo $GLOBALS["curRegion"]["name"]; // does not work
}
Upvotes: 0
Views: 175
Reputation: 7153
Thanks to @lawrencecherone for pointing out that I need to break;
out of the loop.
Without the brake, the loop continues and overrides $curRegion
with null after it is successfully set in the loop.
Note: if by stroke of luck your matched $item
happened to be the very last item in the loop, then it wouldn't get overridden, but... yeah... just add break;
foreach ($regionsArr as $item) {
if ($item['region'] == $param) {
$curRegion = $item;
break; // this kills the loop after $item['region'] matches $param
} else {
$curRegion = null;
}
}
I believe there is a more condensed way to do the above using array_filter or another method, and I welcome it as the solution.
Upvotes: 0