Trying to add up numbers in PHP for loop - php

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)
}
}

Related

get rid of "dividing by zero" warning in sessions

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.

php First value of array not displaying

I have the following bit of code and for some reason in the first WHILE loop the first value of $actor_list (when $i = 0) does not display. If I simply echo $actor_list[0] then it displays fine, but in the loop it will not display. I merely get [td][/td] as the output. The remaining values of the array display fine.
Also the line
echo '</tr><tr> </br>';
is not displaying.
What am I missing here? The value of $num_actors is an even number in my test scenario so there doesn't seem to be a reason for the above echo line to be skipped.
$actor_list = explode(" ", $actors);
$num_actors = count($actor_list);
if ($num_actors <= 6) {
foreach ($actor_list as $actor) {
echo '[td]'.$actor.'[/td] </br>';
}
} elseif ($num_actors <= 12) {
if ($num_actors % 2 == 0) {
$half_actors = $num_actors / 2;
while ($i <= ($half_actors - 1)) {
echo '[td]'.$actor_list[$i].'[/td] </br>';
$i++;
}
echo '</tr><tr> </br>';
while ($i <= $num_actors) {
echo '[td]'.$actor_list[$i].'[/td] </br>';
$i++;
}
}
}
You're not initialising the variable $i to 0, which means it will be set to 'null' and thus not reference the 0th index of the array; but when it's then incremented its value will become 1.
Note: [..] Decrementing NULL values has no effect too, but incrementing them results in 1.
See: http://php.net/manual/en/language.operators.increment.php
Try adding:
$i = 0;
before the if statement.
Made a few changes.
This is working for me.
Try it out.
<?php
$actor_list = 'act1 act2 act3 act4 act5 act6';
$actors = explode(" ", $actor_list);
$num_actors = count($actor_list);
//debug
//echo "<pre>";
//print_r($actor_list);
//echo "</pre>";
echo "<table>";
if ($num_actors <= 6) {
foreach ($actors as $actor) {
echo '<tr><td>'.$actor.'</td></tr>';
}
} elseif ($num_actors <= 12) {
if ($num_actors % 2 == 0) {
$half_actors = $num_actors / 2;
while ($i <= ($half_actors - 1)) {
echo '<tr><td>'.$actor_list[$i].'</td></tr>';
$i++;
}
while ($i <= $num_actors) {
echo '<tr><td>'.$actor_list[$i].'</td></tr>';
$i++;
}
}
}
echo "</table>";
?>

Role a 6 to win! PHP Code

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.

A Logical Algorithm In PHP

I'm a beginner learning PHP. I have tried to make a loop that has a different behaviour for both even and odd numbers. I've been playing around with it for a while, yet I still can't get it to work. Has anyone got a solution?
$count = 0;
$mod = $count % 2;
while ($count < 10)
{
if ($mod == 0) {
echo "even, ";
} else {
echo "odd, ";
}
$count++;
}
A silly mistake, mod inside while() loop.
$count = 0;
while ($count < 10) {
$mod = $count % 2; //Here
if ($mod == 0) {
echo "even, ";
} else {
echo "odd, ";
}
$count++;
}
$count = 0;
$mod = $count %2;
Is were your problem is.
You have to use the modulus (%) operator inside the for loop. Also, there is no need to store the value from the use of the modulus operator at all, it can be compared directly inside the for-loop.
for ($count = 0; $count < 10, $count++) {
if ($count % 2 == 0) {
echo "even, ";
} else {
echo "odd, ";
}
}
You can also switch the while to a for like this.
Welcome to PHP.
Edit #1:
As you are getting a new value of $count every execution of the for-loop the old value if $count % 2 will be incorrect. It has to recalculate for every $count. First it checks if 0 is divisible by 2, then onto 1 and so forth. For every value of $count you have to check the divisibility.
In most programming languages you aren't computing a variable onto another, instead you are taking the value of the variable. Like $a = $b + $c; in that case, if you change the value of $b or $c it does not automatically update $a. Instead you have to call $a = $b + $c again. It is the same with % operator.
$count = 0;
while ($count < 10) {
$mod = $count % 2;
if ($mod == 0) {
echo "even, ";
} else {
echo "odd, ";
}
$count++;
}
use for loop instead of while loop
for($count=0;$count<10;$count++)
{
if(($count % 2) == 0)
echo "even,";
else
echo "odd,";
}

variable increment doesn't work

When I launch my web page, increment doesn't work correctly!
It should go like this: $i = from 1 to x (0,1,2,3,4,5,6 etc..).
But instead it jumps over every step giving result of (1,3,5,7 etc..).
Why is this code doing this?
<ul class="about">
<?php
$result = mysql_query("SELECT * FROM info WHERE id = 1");
while ($row = mysql_fetch_assoc($result))
{
$bioText = $row['bio'];
}
$endBioTxt = explode("\n", $bioText);
for ($i=0; $i < count($endBioTxt);)
{
if (checkNum($i) == true)
{
echo "<li class='left'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
else
{
echo "<li class='right'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
$i++;
}
// Function to check if number is prime
function checkNum($num){
return ($num % 2) ? TRUE : FALSE;
}
?>
</ul>
Output:
Sometext!(right side)
0
1
Sometext2!(right side)
2
3
...
Please DONT do this as other suggested:
for ($i=0; $i < count($endBioTxt); $i++)
do this:
$count = count($endBioTxt);
for ($i=0; $i < $count; $i++) {
}
No need to calculate the count every iteration.
Nacereddine was correct though about the fact that you don't need to do:
$i++;
inside your loop since the preferred (correct?) syntax is doing it in your loop call.
EDIT
You code just looks 'strange' to me.
Why are you doing:
while ($row = mysql_fetch_assoc($result))
{
$bioText = $row['bio'];
}
???
That would just set $bioText with the last record (bio value) in the recordset.
EDIT 2
Also I don't think you really need a function to calculate the modulo of a number.
EDIT 3
If I understand your answer correctly you want 0 to be in the left li and 1 in the right li 2 in the left again and so on.
This should do it:
$endBioTxt = explode("\n", $bioText);
$i = 0;
foreach ($endBioTxt as $txt)
{
$class = 'left';
if ($i%2 == 1) {
$class = 'right';
}
echo '<li class="'.$class.'"><div>'.$txt.'</div></li>';
echo $i; // no idea why you want to do this since it would be invalid html
$i++;
}
Your for statement should be:
for ($i=0; $i < count($endBioTxt); $i++)
see http://us.php.net/manual/en/control-structures.for.php
$i++; You don't need this line inside a for loop, it's withing the for loop declaration that you should put it.
for ($i=0; $i < count($endBioTxt);$i++)
{
if (checkNum($i) == true)
{
echo "<li class='left'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
else
{
echo "<li class='right'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
//$i++; You don't need this line inside a for loop otherwise $i will be incremented twice
}
Edit: Unrelated but this isn't how you check whether a number is prime or not
// Function to check if number is prime
function checkNum($num){
return ($num % 2) ? TRUE : FALSE;
}
This code works, please test it in your environment and then uncomment/comment what you need.
<?php
// This is how query should look like, not big fan of PHP but as far as I remember...
/*
$result = mysql_query("SELECT * FROM info WHERE id = 1");
$row = mysql_fetch_assoc($result);
$bioText = $row['bio'];
$endBioTxt = explode("\n", $bioText);
*/
$endBioTxt[0] = "one";
$endBioTxt[1] = "two";
$endBioTxt[2] = "three";
$endBioTxt[3] = "four";
$endBioTxt[4] = "five";
$totalElements = count($endBioTxt);
for ($i = 0; $i < $totalElements; $i++)
{
if ($i % 2)
{
echo "<li class='left'><div>".$endBioTxt[$i]."</div></li>";
}
else
{
echo "<li class='right'><div>".$endBioTxt[$i]."</div></li>";
}
/*
// This is how you should test if all your array elements are set
if (isset($endBioTxt[$i]) == false)
{
echo "Array has some values that are not set...";
}
*/
}
Edit 1
Try using $endBioTxt = preg_split('/$\R?^/m', $bioTxt); instead of explode.

Categories