0

I suspect the answer to this is incredibly simple and I am bracing myself for a down vote, however, having read this about changing values, trying to implement array_replace() and trying out the 'passing by reference' I have have not solved my simple problem.

$levelState is a 16 item array populated via array_push with either a string 'locked' or 'unlocked', which may print something like this:

Array ( [0] => unlocked [1] => unlocked [2] => locked [3] => locked [4] => locked [5] => locked [6] => locked [7] => locked [8] => locked [9] => locked [10] => locked [11] => unlocked [12] => unlocked [13] => unlocked [14] => unlocked [15] => unlocked )

Under certain circumstance levels below a certain level should be unlocked.

//Function to unlock lower levels if, manually passed. 
function unlockLowerLevels($x) {
    while($x > 0) {
        $levelState[$x] = 'unlocked';
        echo $x;
        $x--;
    }
}
unlockLowerLevels($int);

This function does not make any change to array elements, but does echo a countdown. I would appreciate any help. Thanks.

Russell
  • 655
  • 2
  • 9
  • 21

1 Answers1

3

You need to pass $levelState into the function, see PHP: Variable Scope. So either pass it by reference:

function unlockLowerLevels(&$array, $x) {
    while($x > 0) {
        $array[$x] = 'unlocked';
        echo $x;
        $x--;
    }
}
unlockLowerLevels($levelState, $int);

Or return the new array:

function unlockLowerLevels($array, $x) {
    while($x > 0) {
        $array[$x] = 'unlocked';
        echo $x;
        $x--;
    }
    return $array;
}
$levelState = unlockLowerLevels($levelState, $int);
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
  • 2 remarks: First it should be $x >= 0 because array start with 0 so it could be possible that also levelState[0] can be unlocked, second because all lower level should be unlooked you can include an if($arrray == 'unlocked') break; in your loop, so you can stop on the first unlocked level – Thomas Jun 02 '17 at 22:34
  • 1
    First, maybe, OP didn't give enough detail I'll let them figure that out. Second, how do we know "they should be unlocked" already? – AbraCadaver Jun 02 '17 at 22:50