Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

Php Question

  • 03-02-2013 11:56AM
    #1
    Closed Accounts Posts: 446 ✭✭


    Hi all

    Doing php in college and have been asked to create a coin toss program whereyou win if you get two heads in a row. Thought I had it, but I keep getting the"Undefined offset: 0 on line 16" error which seems to mean that that$check is getting decremented even when $i is not greater than two, which meansthe ‘if’ is getting ignored, but why?

    Sorry if this a real basic question, only started programming, still trying to get my head around the logic, have to say I’m am loving itthough.


    [php]
    <?php
    $tosses = array();
    $numTosses = 4;
    for($i = 1;$i <= $numTosses; $i++) {
    $coin = rand(0,1);
    if ($coin == 0)
    {
    $tosses[$i] = "Heads";
    if ($i >= 2); //seems to be ignored
    {
    $check = $i - 1;
    if($tosses[$check] == "Heads")
    {
    echo "You got two heads in a row, you won";
    exit();
    }
    }
    }

    else {
    $tosses[$i] = "Tails";
    }

    }
    echo "Sorry didnt win this time";

    ?>

    [/php]


Comments

  • Registered Users, Registered Users 2 Posts: 40,038 ✭✭✭✭Sparks


    Devi wrote: »
    [php]
    if ($i >= 2); //seems to be ignored
    [/php]
    It's the semicolon. Remove it...


  • Closed Accounts Posts: 446 ✭✭Devi


    Sparks wrote: »
    It's the semicolon. Remove it...
    oh dear lord, how did I not see that. Thanks Sparks.


Advertisement