I am currently trying to learn PHP and am stuck on a do/while with else/if loop and am totally baffled. Would appreciate if anybody could let me know where i am going wrong with this.
<?php
$rollCount = 0;
$sixCount = false;
do {
echo "<p>So you want to roll a 6 ? </p>";
} while($sixCount == false);
$roll = rand(1,6);
$rollCount ++;
if($roll != 6) {
$sixCount = false;
echo "<p>You just rolled a " .$roll. " .</p>";
}
else {
$sixCount = true;
echo "<p>Nice, you just rolled a 6</p>";
}
echo "<p>It took {$rollCount} rolls to land 6... What are the odds!</p>";
?>
I think i may have written an infinite loop, as the preview screen i am working on just shows loading animation.
My little mind tries to look at it like this.
While $sixCount is equal to false, $roll a random number between 1 and 6 and add a +1 to roll count.
IF the $roll does not = to 6, than the $sixCount is false and print "you just rolled a $roll" or else $sixCount is true and you just rolled a 6.
I try to simplify it in my mind by putting into a sentence and transferring it into PHP. Is this the wrong way to look at PHP ?
Appreciate all help on this. Thanks!!
I think you're misunderstanding the concept of the do...while loop. You need to put all your conditions and output into the do part, and the while part simply defines the condition that should allow the do set to keep looping.
Try shifting your code under the while line into the do statement:
$rollCount = 0;
$sixCount = false;
echo "<p>So you want to roll a 6 ? </p>";
do {
$roll = rand(1,6);
$rollCount++;
if($roll != 6) {
$sixCount = false; // this line is unnecessary
echo "<p>You just rolled a {$roll}.</p>";
}
else {
$sixCount = true;
echo "<p>Nice, you just rolled a 6</p>";
}
} while($sixCount == false);
echo "<p>It took {$rollCount} rolls to land 6... What are the odds!</p>";
An alternative, using the while construct without do would possibly be more applicable to the way you've laid out your code:
$rollCount = 0;
$sixCount = false;
echo "<p>So you want to roll a 6 ? </p>";
while ($sixCount == false) {
$roll = rand(1,6);
$rollCount++;
if($roll != 6) {
$sixCount = false; // this line is unnecessary
echo "<p>You just rolled a {$roll}.</p>";
}
else {
$sixCount = true;
echo "<p>Nice, you just rolled a 6</p>";
}
}
echo "<p>It took {$rollCount} rolls to land 6... What are the odds!</p>";
It appears that you are writing the code you want to continuously execute until it rolls a 6 is outside of the while loop, this is what the code should look like.
<?php
$rollCount = 0;
$sixCount = false;
echo "<p>So you want to roll a 6 ? </p>";
do{
$roll = rand(1,6);
$rollCount ++;
if($roll != 6) {
$sixCount = false;
echo "<p>You just rolled a " .$roll. " .</p>";
}
else {
$sixCount = true;
}
}while($sixCount == false);
echo "<p>Nice, you just rolled a 6</p>";
echo "<p>It took {$rollCount} rolls to land 6... What are the odds!</p>";
?>
Related
I've been working on a console-based Hangman Game with PHP and have come across a somewhat big issue.
When the user guesses the correct word, it functions as needed. It reveals the letter and continues to ask the user to guess the next.
Now, the issue comes when the player gets it wrong. My intentions were when the user gets a letter wrong, the $playerErrors variable gets +1 value, and once $playerErrors has a value of 6, aka the player has made 6 wrong guesses, the program terminates. This is not what happens however, instead, if the word they're guessing has 5 letters for example, and they guessed 1 letter wrong, they will get +5 $playerErrors instead of just +1 $playerErrors.
So as a result of the player getting say 5 $playerErrors in one guess, the player will really only have 1 or 2 lives instead of 6.
Here is the code from the main section:
while ($playerErrors < 6) {
if (strpos($shwWord, '_') === false){
echo "You won! Congratulations!\n";
break;
}
$guess = readline('Guess a letter: ');
for ($g = 0; $g < count($secretArray); $g+=1) {
if ($guess === $secretArray[$g]){
$displayedLetters[$g] = $guess;
}
else{
$playerErrors += 1;
echo "Errors: " . $playerErrors;
echo "\n";
}
}
$shwWord = implode(' ', $displayedLetters);
echo "\n $shwWord \n\n";
}
if ($playerErrors >= 6) {
echo "you lost" . PHP_EOL;
}
You are incrementing the errors within your 'check letters' loop, meaning that you increment once for each 'wrong letter'.
Try this code:
while ($playerErrors < 6) {
if (strpos($shwWord, '_') === false){
echo "You won! Congratulations!\n";
break;
}
$guess = readline('Guess a letter: ');
$foundLetter = false;
for ($g = 0; $g < count($secretArray); $g+=1) {
if ($guess === $secretArray[$g])
{
$displayedLetters[$g] = $guess;
$foundLetter = true;
}
}
if (!$foundLetter)
{
$playerErrors += 1;
echo "Errors: " . $playerErrors;
echo "\n";
}
$shwWord = implode(' ', $displayedLetters);
echo "\n $shwWord \n\n";
}
if ($playerErrors >= 6) {
echo "you lost" . PHP_EOL;
}
I'm new to php and have been struggling to get my rock, paper, scissors game to work! I know what I'm trying to do but just can't get my head aound where I've gone wrong......it works for rock but for paper and scissors I'm getting two outputs!!Please help a novice out...thanks!!
P.S I know there are much slicker ways of doing this!!
<?php
// user enters a value R P or S - NEED TO RETURN A COUPLE OF
TIMES AFTER, not sure why?
echo "What do you select - R for rock, P for paper or S for
scissors?\n";
$input=
$R = stream_get_line(STDIN, 1, "\n");
$P = stream_get_line(STDIN, 1, "\n");
$S = stream_get_line(STDIN, 1, "\n");
//program converts the value into Rock, Paper or Scissors
switch ($input) {
case 'R' :
case 'r':
echo $R = "You selected Rock\n" ;
break;
case 'P' :
case 'p':
echo $P = "You selected Paper\n" ;
break;
case 'S' :
case 's':
echo $S = "You selected Scissors\n" ;
break;
}
//computer generates a random value 0,1,2 & converts to R P or S
echo "\nComputer is now making its selection....\n";
//$options = ('Rock=0, Paper=1, Scissors=2');
$output = (rand(0,2) );
echo $output;
if ($output== 0)
{
echo "\nComputer Selected Rock\n"; //goto Rock;
}
elseif ($output==1)
{
echo "\nComputer Selected Paper\n"; //goto Paper;
}
elseif ($output==2)
{
echo "\nComputer Selected Scissors\n"; //goto Scissors;
}
//compare user and computers choise
Rock:
if ($R && $output===0)//.($P && $output==1),($S && $output==2))
{
echo "\nITS A DRAW";
}
elseif ($R && $output===1)//.($P && $output==2).($S &&
$output==0))
{
echo "\nCOMPUTER WINS";
}
elseif ($R && $output===2)//.($P && $output==0).($S &&
$output==1))
{
echo "\nYOU WIN";
}
Paper:
if ($P && $output===1)
{
echo "\nITS A DRAW";
}
elseif ($P && $output===2)
{
echo "\nCOMPUTER WINS";
}
elseif ($P && $output===0)
{
echo "\nYOU WIN";
}
Scissors:
if ($S && $output===2)
{
echo "\nITS A DRAW";
}
elseif ($S && $output===0)
{
echo "\nCOMPUTER WINS";
}
elseif ($S && $output===1)
{
echo "\nYOU WIN";
}
You should inicialize $R, $P and $S to false first. Then read user input 1x into $input.
The rest of the script seams to be ok.
<?php
$R = $P = $S = false;
$input= stream_get_line(STDIN, 1, "\n");
// user enters a value R P or S - NEED TO RETURN A COUPLE OF TIMES AFTER, not sure why?
because
$input=
$R = stream_get_line(STDIN, 1, "\n");
$P = stream_get_line(STDIN, 1, "\n");
$S = stream_get_line(STDIN, 1, "\n");
You're calling stream_get_line() three times so your script wants three lines of input.
Also, I'm not sure if this was intended, but you're getting your user input seemingly purely by chance as $input = $R = stream_get_line() stores the first user input in $R and $input.
I'd suggest only doing $input = stream_get_line() and nothign else.
Then in your switch/case block you do e.g. echo $R = "..."; and further down you do if ($R && ...).
Evaluating strings as booleans is not recommended.
I would recommend something like
$R = $P = $S = false; // initialize all variables to false
switch ($input)
{
case "R":
$R = true; // set selected variable to true
echo "You have selected Rock\n";
break;
// ...
}
Finally, you seem to be using jump marks to comment your code.
Rock:
if ( ...
While this doesn't cause any problems (yet), it's generally considered bad style to abuse language features for documentation purposes.
These should become comments:
// Rock
if ( ...
How to execute php if condition once time only and didn't check it again, i put if condition in for loop and i want to check it one time only:
<?php
for($x=0;$x<3;$x++){
if($x == $x){
echo "";
}
else{
echo "hidden";
}
}
I need to execute first if one time only in for loop
I need to execute first if one time only in for loop. Well that's not how you do it, you need to compare with a variable and upon success just use break to come out of the loop. Something like:
<?php
$y = 0;
for($x=0; $x<3; $x++){
if($x === $y){
echo "X is Equal to Y";
break;
}
else {echo "hidden";}
}
echo "<br>". "You're outside the loop!";
?>
Set a flag, if flag is true don't execute if condition.
<?php
$flag = 0;
for($x=0;$x<3;$x++) {
if($x == $x && $flag == 0){
echo "";
$flag = 1;
}
else{
echo "hidden";
}
}
<?php
$i=1;
while ($i<=$totalpages) {
if (($i>=($page-5) && $i<=($page+5) && $i<$totalpages) || $i==1 || ($i+1>$totalpages)) {
echo "<td><a href=\"search.php?page=$i\">";
if ($i=$page) {
echo "<strong> $i </strong>";
}
if ($i!=$page) {
echo " $i ";
}
echo "</a></td>";
}
$i++;
}
?>
Trying to build a webpage that ouputs some search values neat the bottom of the page, however I keep getting an infinite loop. I've no Idea about what's causing it, and would like someone elses insight into the problem at hand.
Your if condition has a problem
Change
$i =1
with
$i==1
You have a number of places that you reset $i, inadvertently I assume
$i=1
and
$i=$page
replace them with ==
<?php
$i=1;
while ($i<=$totalpages) {
if (($i>=($page-5) && $i<=($page+5) && $i<$totalpages) || $i == 1|| ($i+1>$totalpages)) {
echo "<td><a href=\"search.php?page=$i\">";
if ($i == $page) {
echo "<strong> $i </strong>";
}
if ($i!=$page) {
echo " $i ";
}
echo "</a></td>";
}
$i++;
}
?>
Changes in 1st and second if condition.
1) $i == 1
2) $i == $page
is there a reason why this can not be accomplished using a for loop ? While loops are always risky and easy to cause problems if there is a scenario to cause to loop for ever.
eg.
for ($i = 0; $i<=$totalpages; $i++){
// do something
}
There is some issues in the conditions
first: the
|| $i=1||
allways return true.
Change for
|| $i==1||
Second: The same case of adobe
if ($i=$page) //Allways return try is assignation operation
Change to:
if ($i==$page)
Got this code which is troubling me and am eager to accept any help!
$x=0;
while($row = mysql_fetch_array($result))
{
if ($me == $x)
{
echo "You are $me";
break;
}
else
{
$x++;
}
}
When I include the break; it returns :
You have selected the 1
However, when I remove the break; it returns
You have selected the 1 You have selected the 1 You have selected the 1 You have selected the 1
There are currently 6 records in the database and if the code were to work it would display "You are 4th"
Any ideas?
Your $x++; only executes on else. In order to have it increment on every iteration you need to remove the else:
$x=0;
while($row = mysql_fetch_array($result))
{
if ($me == $x)
{
echo "You are $me";
break;
}
$x++;
}
Just a side note: $row doesn't seem to be related to $me and $x here. I'll assume your loop contains some other code that you've omitted, but this alone will probably answer your question.
You are icrementing $x in the else, this is never getting executed.
You need to do the increment in the same part as the echo.
So either:
$x=0;
while($row = mysql_fetch_array($result))
{
if ($me == $x)
{
echo "You are $me";
$x++;
}
else
{
$x++;
}
}
Or if you never need to increment $x without echoing:
$x=0;
while($row = mysql_fetch_array($result))
{
if ($me == $x)
{
echo "You are $me";
x++;
}
}