Unexpected 'global' error

Hello guys!
I am getting a parse error: syntax error, unexpected ‘global’ (T_GLOBAL) at the line starting with for :


echo "test";

$speed = 15;

//$distanceArray = [];

$distanceArray = array_fill(0, 40, 0);


$nextIteration = 0;

function cycleWithStep(int $step) {
    for ($counter = global $nextIteration; $counter < $step; $counter++) {
     global $distanceArray[$counter]++;   
    global $nextIteration = $counter;



You really need to learn about variable scope ( https://www.php.net/manual/en/language.variables.scope.php
) and why are you using global when it looks like you are having most everything is a global variable?

function cycleWithStep($step) {
  for ($counter= 0; $counter <= $step; $counter++) {
      $x += 1;
      $distanceArray[$counter] = $x;
  } // End of for loop:
  return $distanceArray; // return the array:
} // end of function:

$resultArray = cycleWithStep(15); // Call Function:

echo "<pre>" . print_r($resultArray, 1) . "</pre>";

I would fool around with the above and I just want to note that I didn’t test it out. Though that would be a good way to learn debugging it. I just like to add I avoid global variables at all costs as I’m old school. I think global variables should be avoided at all costs as it leads to bad coding practices. I have found out while it solves a problem with code you are developing that you really don’t understand why it doesn’t work in the first place. It’s a band aid. It only gets worse when you start learning PHP Object-Oriented Programming if you frequently use global variables as there are short cuts in OOP as well.

Sponsor our Newsletter | Privacy Policy | Terms of Service