Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why code goes to infinite loop? (

Tags:

loops

php

<?php
$mines = 10;

####
for($x=1; $x<=9; $x++) {
    for($y=1; $y<=9; $y++) {
        $minefield[$x][$y] = 0;
    }
}       

for($i=0; $i<$mines; $i++) {
    $randx = rand(1, 9);
    $randy = rand(1, 9);

    if($minefield[$randx][$randy] == 'X') {
        $i--;
    } else {
        $minefield[$randx][$randy] = 'X';
    }
}

What's i doing wrong?

like image 982
kopaty4 Avatar asked May 16 '26 05:05

kopaty4


1 Answers

When comparing strings (or resources) with integers, strings are translated to numbers first, as per the documentation, then compared.

As such, this:

if ($minefield[$randx][$randy] == 'X')

... where $minefield[$randx][$randy] = 0 is equivalent to:

if (0 == 0) // 0 == (int)'X'

... which is always true. Therefore, you are incrementing and decrementing $i at each iteration.

like image 56
netcoder Avatar answered May 18 '26 18:05

netcoder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!