I'm currently learning how to use do/while loops in PHP through codeacademy. I'm working on a challenge where you create a six-sided die and continue rolling until you get a six. Here's what I've come up with so far:
<?php
$roll = 1;
do {
echo “Roll Number " . $roll . ". Begin rolling for a 6.";
} while ($roll != 6); {
for ($rollNumber = 1; $roll != 6; $roll ++) {
$roll = rand(1, 6);
echo "On roll number " . $rollNumber . "You got a " $roll ".\n";
};}
?>
I though the best way to get started is by creating a roll variable that we can use once for the do loop to check if it's working:
$roll = 1;
I set the value to one instead of zero, because there's no zero number on a die, and we'll assume the player first rolls a one. Next I want to check if the do loop is working so I echo the following:
do {
echo “Roll Number " . $roll . ". Begin rolling for a 6.";
}
After making sure the do loop worked, I create the while condition:
while ($roll != 6) {
Then I want to create a rollNumber variable to keep track of what roll I'm on and increment it:
for ($rollNumber = 1; $roll != 6; $roll ++) {
next I set the value of the roll variable so that it generates a random number between 1 and 6:
$roll = rand(1,6);
Finally I want to echo the message "On roll number you got a ." :
echo “On roll number “ . $rollNumber . "You got a " $roll “.\n";}
For some reason the code's not working. Any suggestions or help would be much appreciated! Thanks.
You were on the right track with a while loop and rand(). The only other thing you needed was to set a count variable to display the roll number (you can just increment this variable on every "roll").
Your code could be simplified to this:
$c = $n = 1;
while ($n != 6) {
echo 'on roll number ' . $c++ . ' you rolled a ' . $n = rand(1, 6) . "\n";
}
Here's an example
You've made this way too complicated. There's no need for two loops.
$rolled = 0;
$numbers = range(1, 6); //generate array with 1-6
$counter = 0;
while($rolled!=6)
{
$counter++;
shuffle($numbers); //shuffle array
$rolled = $numbers[0]; //grab first item
echo '<br/>(Roll ' . $counter . ') ' . $rolled;
}
Why not have a function that returns the result of a roll, and then a loop that calls this function until it returns a 6?
<?php
function roll() {
return mt_rand(1, 6);
}
$roll = 1;
do {
if (roll() == 6) {
printf('You rolled a 6 on roll %d.', $roll);
break;
}
$roll++;
} while (0);
This do/while loop continues until the roll() function returns a 6.
Related
I have this code that works but is missing some details
$input=7;
$k=($input+1)/2;
for($i=1;$i<=$input;$i++){
for($j=1;$j<=$input;$j++){
if($j==($input+1)/2 || $j==$k || $j==$input-$k+1){
echo "*";
}
else{
echo "-";
}
}
echo "<br>";
$k++;
}
And the output look like this
---*---
--***--
-*-*-*-
*--*--*
---*---
---*---
---*---
My desired output is
___*___
__***__
_*****_
*******
__***__
__***__
__***__
In your if statement you have three conditions. So there can only be three stars in a row.
I think your structure is more complex as it should be. You could use str_repeat instead. Something like this:
$input=7;
for($i=1;$i<=$input;$i+=2) {
echo str_repeat('-', ($input - $i) / 2 ) .
str_repeat('*', $i) .
str_repeat('-', ($input - $i) / 2 ) .
'<br>';
}
$shaft = floor($input / 2);
for($i=1;$i<$input/2;$i++) {
echo str_repeat('-', ($input - $shaft) / 2 ) .
str_repeat('*', $shaft) .
str_repeat('-', ($input - $shaft) / 2 ) .
'<br>';
}
The first loop draws the triangle which is growing by 2 each row.
The second loop draws the shaft.
So if you need to do it only using loops and if else, you have to elaborate your if statement. Here's my solution:
$input = 7;
for($i=1;$i<=2*$input;$i+=2) {
for($k=1;$k<=$input;$k++) {
if(($i <= $input && $k > floor(($input - $i)/2) && $k <= ceil(($input + $i)/2)) ||
($i > $input && $k > ceil($input/4) && $k <= floor(3/4*$input))) {
echo "*";
} else {
echo "-";
}
}
echo "<br>";
}
Note: In the first loop I use $i+=2, so with every iteration $i increases by two. To get the right number of lines the loop continues till 2*$input.
The if statement has two parts. In the first part the triangle is drawn (adding two stars every row since $i increases by 2). In the second part, when $i becomes greater than $input, drawing the shaft, which is half the width and 1/4 of the width on each side.
I got the answer guys, thank you all.
$x=($input/2); $y=$x+1; $w=($input/2);
if($w%2==0) {
$w++;
}
for($i=1; $i<=$input; $i++) {
for($j=1; $j<=$input; $j++) {
if($j>=$x && $j<=$y) {
echo "*";
}
else {
echo "_";
}
}
if($i>(($input-1)/2)) {
$x=(($input-$w)/2)+1;
$y=($x+$w)-1;
}
else {
$x--;
$y++;
}
echo "<br>";
}
I am beginning to learn PHP. Here I am trying to create a loop that checks whether a randomly generated number is 50. If the number is 50, I want to print "it's 50!", if not, I want to echo the result, then repeat the random generation.
Here is my code:
<?php
$number = 0; // sets the number to 0
while ($number != 50) { // I want this loop to repeat when the result isn't 50
echo $number; // print the result
$number = rand(0,100); // reshuffle
if ($number == 50) { // result for if 50 is the result
echo "it's 50!";
}
else { // result otherwise
$number = 0;
}
}
?>
I feel like it's not working because I don't redefine $number based on the result of the rand function, is this correct? If so, how do I redefine the value of the $number variable from within the loop?
The main issue with the code you have submitted is that, if your randomly picked number is not 50 you then assign 0 to it. So your output will be a stream of 0s.
You can modify your code slightly, and drop your else block:
<?php
$number = null;
while ($number != 50) {
$number = rand(0, 100);
echo $number . "\n";
if ($number == 50)
echo "It's 50!";
}
Or, just loop until you strike your number, then break out.
<?php
while (true) {
$number = rand(0, 100);
echo "$number\n";
if ($number == 50) {
echo "it's 50!\n";
break;
}
}
Or even simpler:
while (($number = rand(0, 100)) != 50)
echo "$number\n";
echo "It's 50!";
I'm trying to add up all numbers that are output in my code, how can I do this?
$tall1 = 0;
for ($tall1=0; $tall1 <= 100; $tall1++) {
if ($tall1 % 3 == 0) {
echo $tall1 . " ";
$tall++;
}
}
$total = 0; //initialize variable
for ($tall1=0; $tall1 <= 100; $tall1++) {
if ($tall1 % 3 == 0) {
echo $tall1 . " ";
$total += $tall1; //add the printed number to the previously initialized variable. This is the same as writing $total = $total + $tall1;
}
}
echo "total: ".$total; //do something with the variable, in this case, print it
Some notes about your initial code:
$tall1 = 0; //you don't need to do this, it is done by the for loop
for (
$tall1=0; //this is where $tall1 is initialized
$tall1 <= 100;
$tall1++ //this is where $tall1 is incremented every time
) {
if ($tall1 % 3 == 0) {
echo $tall1 . " ";
$tall++; //this variable is not used anywhere. If you meant $tall1, then you don't need to do this, it is done by the for loop. If you did not mean $tall1, but wanted to count how many times the if statement runs, then you need to initialize this variable (place something like $tall=0; at the top)
}
}
This is a game of guessing number, I want the page to keep track of the wins, losses and totals and the %of winning by using sessions. I want to reset everything when I click "reset", but when I click reset everything equals to zero and there will be a warning saying "dividing by zero". How do I rearrange this php for it to only do the %calculation when the game is played but not when it's being reset?
<?php
// initialize wins and losses
if ($_SESSION['wins'] == "") {
$_SESSION['wins'] = 0;
}
if ($_SESSION['losses'] == "") {
$_SESSION['losses'] = 0;
}
echo "<h1>PHP SESSIONS</h1>";
if ($_GET['reset'] == "yes") {
$_SESSION['wins'] = 0;
$_SESSION['losses'] = 0;
$_SESSION['total'] = 0;
echo "<p>The game has been reset.</p>";
} else {
$randNum = rand(1,5);
echo "<p>The random number is <b>" . $randNum . "</b></p>";
if ($randNum == 3) {
echo "<p>The number equalled 3. YOU WIN!</p>";
$_SESSION['wins'] = $_SESSION['wins'] + 1;
} else {
echo "<p>The number did NOT equal 3. YOU LOSE!</p>";
$_SESSION['losses'] = $_SESSION['losses'] + 1;
}
$_SESSION['total'] = $_SESSION['total'] + 1;
}
$_SESSION ['percentage'] = (($_SESSION['wins']) / ($_SESSION['total'])) * 100 ;
echo "<p>WINS: " . $_SESSION['wins'] . " | LOSSES: " . $_SESSION['losses'] . "| TOTAL: " . $_SESSION['total'] . "</p>";
echo "<p>Percentage of Winning: ". $_SESSION ['percentage'] . " % </p>"
?>
ROLL AGAIN :)
RESET :)
Move up the line in which you are dividing:
$_SESSION ['percentage'] = (($_SESSION['wins']) / ($_SESSION['total'])) * 100 ;
Put it inside the else bracket. Once I reformatted your code, it was easy to see the problem. I'd advise always using proper indenting. :)
When $_GET['reset'] == 'yes' is satisfied, you are setting $_SESSION['total'] = 0.
Then, you're dividing $_SESSION['wins'] by a 0 valued $_SESSION['total'] in the following line (which is executed regardless of the current state of $_SESSION['total']:
$_SESSION ['percentage'] = (($_SESSION['wins']) / ($_SESSION['total'])) * 100 ;
It's easier to see what's going on when the code is properly formatted. Have a look:
if ($_GET['reset'] == "yes") { // reset called
$_SESSION['wins'] = 0;
$_SESSION['losses'] = 0;
$_SESSION['total'] = 0; // set to zero(0)
echo "<p>The game has been reset.</p>";
} else {
$randNum = rand(1,5);
echo "<p>The random number is <b>" . $randNum . "</b></p>";
if ($randNum == 3) {
echo "<p>The number equalled 3. YOU WIN!</p>";
$_SESSION['wins'] = $_SESSION['wins'] + 1;
} else {
echo "<p>The number did NOT equal 3. YOU LOSE!</p>";
$_SESSION['losses'] = $_SESSION['losses'] + 1;
}
$_SESSION['total'] = $_SESSION['total'] + 1;
}
$_SESSION ['percentage'] = (($_SESSION['wins']) / ($_SESSION['total'])) * 100; // chance that $_SESSION['total'] is zero(0)
So again, when you call the reset action, $_SESSION['total'] is given a value of int(0). Later in the script you then divide by that int(0), giving you the error in question. Make sense?
So you first need to ensure $_SESSION['total'] is greater than 0 before dividing by it.
I have a value as a number. For instance, 502.
I want to write a php if statement that will display some text if the value is lesser or greater than certain numbers, or between a range.
E.g.
number is 502, text will say: "Between 500-600"
number is 56, text will say: "Between 0-60"
etc.
So far I have this:
<?php $count=0;?>
<?php $board = getUserBoard($userDetails['userId']);?>
<?php if(is_array($board)):?>
<?php $boardCount = count($board);?>
<?php foreach($board as $key=>$value):?>
<?php
$boardPin = getEachBoardPins($value->id);
$count = $count + count($boardPin);
?>
<?php endforeach?>
<?php endif?>
And that gives me a number:
<?php echo $count;?>
I have tried writing...
<?php if(($count)): => 500 ?>
Over 500
<?php endif ?>
But I keep running into errors.
I'd like to create a list if possible with elseif statements denoting various number ranges.
E.g.
0-50, 51-250, 251-500 etc.
Can anyone help me?
Thanks.
The sanest, neatest and most widely used syntax for if conditions in PHP is:
if($value >=500 && $value <=600 )
{
echo "value is between 500 and 600";
}
if ($count >= 0 && $count < 100) {
echo 'between 0 et 99';
} elseif ($count < 199) {
echo 'between 100 and 199';
} elseif { ...
}elseif ($count < 599) {
echo 'between 500 and 599';
} else {
echo 'greater or equal than 600';
}
I wrote something like this a few years back (might be a better way to do it):
function create_range($p_num, $p_group = 1000) {
$i = 0;
while($p_num >= $i) {
$i += $p_group;
}
$i -= $p_group;
return $i . '-' . ($i + $p_group - 1);
}
print 'The number is between ' . create_range(502, 100) . '.';
It'll say 500-599, but you can adjust it to your needs.
I'm not sure what you need, but here is what I understand you ask:
function getRange($n, $limit = array(50, 250, 500)) { // Will create the ranges 0-50, 51-250, 251-500 and 500-infinity
$previousLimit = 0;
foreach ($limits as $limit) {
if ($n < $limit) {
return 'Between ' . ($previousLimit + 1) . ' and ' . $limit; //Return whatever you need.
}
$previousLimit = $limit;
}
return 'Greater than ' . $previousLimit; // Return whatever you need.
}
echo getRange(56); // Prints "Between 51 and 250"
echo getRange(501); // Prints "Greater than 500"
echo getRange(12, array(5, 10, 15, 20)); // Prints "Between 11 and 15"
function getRange($number){
$length=strlen($number);
$length--;
$r1=round($number,-$length);
if ($r1>$number){
$r2=$r1-pow(10,$length);
return ''.$number.' value is between '.$r2.'-'.$r1;
}
else {
$r2=$r1+pow(10,$length);
return ''.$number.' value is between '.$r1.'-'.$r2;
}
}
Try this.