PHP elseif

  • alex89
  • Bronze Member
  • Bronze Member
  • User avatar
  • Posts: 239
  • Loc: Western Australia

Post 3+ Months Ago

Is there an easier way to do the following?
$gamerno varies from 1-5 (and sometimes null), and $game# are strings set elsewhere.

Code: [ Select ]
    if($gameno == 1) {echo $game1;
    }
    elseif($gameno == 2) {echo $game2;
    }
    elseif($gameno == 3) {echo $game3;
    }     
    elseif($gameno == 4) {echo $game4;
    }     
    elseif($gameno == 5) {echo $game5;
    }
    else {echo "<br />Please choose a game<br /><br />";}
  1.     if($gameno == 1) {echo $game1;
  2.     }
  3.     elseif($gameno == 2) {echo $game2;
  4.     }
  5.     elseif($gameno == 3) {echo $game3;
  6.     }     
  7.     elseif($gameno == 4) {echo $game4;
  8.     }     
  9.     elseif($gameno == 5) {echo $game5;
  10.     }
  11.     else {echo "<br />Please choose a game<br /><br />";}
  • Anonymous
  • Bot
  • No Avatar
  • Posts: ?
  • Loc: Ozzuland
  • Status: Online

Post 3+ Months Ago

  • joebert
  • Fart Bubbles
  • Genius
  • User avatar
  • Posts: 13502
  • Loc: Florida

Post 3+ Months Ago

I'm on my way to bed and not entirely sure about the sprintf line, but perhaps this will give you an idea. :)

Code: [ Select ]
$_game = sprintf('game%u', $gameno);
if(isset($$_game))
{
echo $$_game;
}
else
{
echo 'choose game num';
}
  1. $_game = sprintf('game%u', $gameno);
  2. if(isset($$_game))
  3. {
  4. echo $$_game;
  5. }
  6. else
  7. {
  8. echo 'choose game num';
  9. }
  • alex89
  • Bronze Member
  • Bronze Member
  • User avatar
  • Posts: 239
  • Loc: Western Australia

Post 3+ Months Ago

Perfect - thanks alot!

Code: [ Select ]
$_game = sprintf('game%u', $gameno);
    if (isset ($gameno)){
    echo $$_game;
    }
    else {echo "Please choose a game";
    }
  1. $_game = sprintf('game%u', $gameno);
  2.     if (isset ($gameno)){
  3.     echo $$_game;
  4.     }
  5.     else {echo "Please choose a game";
  6.     }
  • joebert
  • Fart Bubbles
  • Genius
  • User avatar
  • Posts: 13502
  • Loc: Florida

Post 3+ Months Ago

You really should be checking that the complex variable exists with that isset instead of $gameno like I have it.
If you check $gameno it should be before the sprintf line where the complex variable name is constructed.
  • alex89
  • Bronze Member
  • Bronze Member
  • User avatar
  • Posts: 239
  • Loc: Western Australia

Post 3+ Months Ago

Ah yes, if someone enters a number bigger than my maximum, it'll return nothing, rather than the else echo.

Cheers!

Post Information

  • Total Posts in this topic: 5 posts
  • Users browsing this forum: No registered users and 89 guests
  • You cannot post new topics in this forum
  • You cannot reply to topics in this forum
  • You cannot edit your posts in this forum
  • You cannot delete your posts in this forum
  • You cannot post attachments in this forum
 
cron
 

© 1998-2014. Ozzu® is a registered trademark of Unmelted, LLC.