Brae
Brae

Reputation: 514

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).

Screenshot of console

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.

Upvotes: 0

Views: 255

Answers (1)

bns
bns

Reputation: 384

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.

Upvotes: 1

Related Questions