Déjà vu
Déjà vu

Reputation: 783

PHP Session While loop not working

I have this while loop that keeps repeating the same thing without ever stopping, untill it gives me a whole page of errors.

I'll explain a bit of what im doing: I made a BlackJack game, using only PHP. So with the use of 3 different forms, i start the game ( gives me 2 cards and the dealer 1 card), i create a hit button ( gives me 1 card each time i click it ) and a stand form (which will give the dealer cards ). With the use of sessions i remember all cards so they dont get lost upon a button click. And with the reset button i start and destroy the session, so that a new game is possible. All of this works, except the stand button.

It should give the dealer cards untill his points are => 17. But for some reason it keeps repeating untill my whole page is full of errors. I used some different loops:

if(FORM_stand("Stand")){
   while( $total_dealer < 17){
   draw_dealer_card();
   }
   list_dealer_hand();
}

and

if(FORM_stand("Stand")){
   list_dealer_hand();
   do {
      draw_dealer_card();
   } while ($total_dealer < 17);
}

I used both of them without sucess.

The draw_dealer_card(); looks like this:

function draw_dealer_card() {
    $dealer_card = array_rand($_SESSION["dealer_pile"]);
    $_SESSION["dealer_hand"][$dealer_card] = $_SESSION["dealer_pile"][$dealer_card];
    unset($_SESSION["dealer_pile"][$dealer_card]);
}

And the list_dealer_hand(); like this:

function list_dealer_hand() {
    foreach($_SESSION["dealer_hand"] as $dealer_card=>$points) {
        echo $dealer_card;
        echo ', ';
    }
}

I don't really know what else is important, please let me know if you're missing some information!

Thanks in advance!

Ps: Don't ask why i'm using only PHP, since that's the point of this assignment. (using only, or as much as possible, PHP)

If you're wondering what my erros look like, they come when i press stand, take a couple of seconds to load, then show me these errors over and over again:

Notice: Undefined index: dealer_pile

Trying to destroy uninitialized session

Notice: Undefined index: dealer_pile

EDIT: At the top of my page i run the session_start(); which only get interrupted if i press the reset button.

EDIT:

if(!isset($_SESSION["dealer_pile"])) $_SESSION["dealer_pile"] = array(

  2           =>  2,
  3           =>  3,
  4           =>  4,
  5           =>  5,
  6           =>  6,
  7           =>  7,
  8           =>  8,
  9           =>  9,
  10          =>  10,
  'Jack'      =>  10,
  'Queen'     =>  10,
  'King'      =>  10,
  'Ace'       =>  11);`

Upvotes: 1

Views: 544

Answers (1)

koenoe
koenoe

Reputation: 110

Besides a missing session_start(); you should also set $_SESSION["dealer_pile"]

$_SESSION["dealer_pile"] = "foobar";

Upvotes: 1

Related Questions