简体   繁体   中英

PHP if condition not evaluating correctly

I'm having an issue with some PHP code. Basically I have an array of id values, $challengeIDs , and a value $number which stores the current location in this array (it affects which page is loaded into the body). I want to check that I haven't reached the end of the array before I move to the next ID value.

if (($number+1) < (count($challengeIDs)-1)) {
    $n = $number+1;
    echo "window.location = './challenge.php?n={$n}';";
} else {
    $_SESSION['n'] = 0;
    $_SESSION['playlist'] = "";
    echo "window.location = './index.php';";            
}
echo "});}</script>";

I've put a console.log() statement immediately above this snippet which reports that the value of $number is 1 and count($challengeIDs) is 4. But for some reason the page is going to index.php rather than going to the next page in the list. It may be elsewhere in the code, but any ideas? Anything suggestions are gratefully received :)

EDIT: Here is the console output. The values are output the line before this snippet, and the page changes according to the value. It works no problem from page 1 (n=0) to page 2 (n=1), but fails and goes to index.php going to page 3 (n=2).

控制台的屏幕截图

SOLUTION: Ended up working it out - sorry guys, it wasn't related to this code at all. There was a check elsewhere which was incorrectly resetting the values based on a GET parameter.

This may sound stupid but I think you may be using wrong the if clause In the code I can see

if (($number+1) < (count($challengeIDs)-1)) {

and you wrote that

count($challengeIDs) is 4.

So when page is 3 (n=2) where there is your problem, it goes to the else clause because

if (($number+1) < (count($challengeIDs)-1)) 

means

if ((2+1) < (4-1)) 

and 3 is not lesser than 3. So change the if clause.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM