Search code examples
phparraysservercommand-line-interfacesingle-threaded

PHP: why the value is modified if there is no assign?


Basically there's not too much about it, since I put echo inside my code. It is a CLI script which should be single-threaded.

echo "\$map: ".json_encode($map)."\n\$mapHarvests: ".json_encode($mapHarvests)."\n";

foreach($map as $key => $section)
    if($players[$id]->pos < $section[0])
        break;

    elseif($players[$id]->pos < $section[1] && isset($mapHarvests[$key]))
    {
        $harvesters[$id] = [$currentTime, $key];
        break;
    }

echo "\$map: ".json_encode($map)."\n\$mapHarvests: ".json_encode($mapHarvests)."\n";

This is what the console outputs:

$map: [[-560,-240],[240,560]]
$mapHarvests: [[[0],1],[[1,2,3],1]]
$map: [[-560,-240],[240,560]]
$mapHarvests: [[[0],1],[240,560]]

Why is $mapHarvests modified? I tried to switch isset() with array_key_exists() and the same thing resulted. There is a fancier look at the code:

foreach($map as $key => $section)
    if(sectionStartsAfterPlayerPos())
        break;

    elseif(playerIsInSection() && sectionCanBeHarvested())
    {
        registerPlayer();
        break;
    }

Edit 1: this is how the vars are declared:

$map = [0 => [-560, -240], 1 => [240, 560]];
$mapHarvests = [0 => [[0], 1], 1 => [[1, 2, 3], 1]];
$harvesters = [];
$currentTime = time(); // this one is inside the main loop

Solution

  • I found the problem. In the main loop of the script I also had this thing:

    if($currentTime - $settings->lastHarvestIncrease > 3)
    {
        foreach($mapHarvests as &$section)
            if($section[$timeToHarvest] > 1)
                $section[$timeToHarvest] --;
    
        $settings->lastHarvestIncrease = $currentTime;
        $settings->save();
    }
    

    Seems like changing section to section2 gave the right result. $section was used in just these 2 sections, that are in opposite corners and the scope should've been different, but I guess I didn't understood how references works.