PHP Calculation, break point, and reset value in foreach loop - php

How do you calculate (sum) + a value in foreach loop?
I am working on a cricket application where i have to count the loop for each 6 times and then count specific value and then echo the total.
I have a code not exact but something like this.
And there are two values:
Balls $balls['1']; array like 1,2,3,4,5 and up to 300-1000 balls
Runs $balls['6']; array like 2,3,1,5 random numbers could be any;
Values comes from mysql table columns balls and runs
foreach( $balls as $ball ){
$countball++;
// here is what i need to know how do i calculate the values of $ball + $ball?
// so i can echo it inside the below if condition?
$runs = $ball['runs'] + $ball['runs']; // not working
if($countball == 6){
echo $runs;
}
$runs+= $ball; // reset the ball counting to continue addition from loop?
// and reset the
}// end foreach
however something like this works fine for the first $countball == 6. but after that it does not show the exact value

You forget to reset the $countball.
You may change the if part as :
if($countball == 6)
{
echo $runs;
$countball = 0;
}

Maybe this is what you need:
$runs = 0;
foreach( $balls as $ball ){
$runs += $ball['runs'];
}
echo $runs;

With help of #Barmar from above i got the desired output as followings
$runs = 0;
$countball=0;
foreach( $balls as $ball ){
$countball++;
$runs += $ball['runs'];
if($countball == 6){
// reset runs from current loop runs for next, if i reset $runs = 0
// for some reason it does not (SUM) + this loops $ball['runs'] with last 5;
$runs = $ball['runs'];
$countball=0;
}// end if $countball == 6
}// end foreach
echo $runs;

Related

Finding the averege in a loop counting to 100

I need to find the averege after using a loop counting ever 3rd to a 100. The loop part is easy enough, but I need to sum every value then divide the sum on the total of values.
for ($x = 3; $x < 100; $x+=3) {
echo $x.", ";
}
This is the loop I need to use. How to I sum the values this produces and how do I find how many values this loop produces?
I believe the intention here is to learn about loops, otherwise this stuff can be done without looping too.
For learning purpose, you can simply introduce two variables count and sum and compute them inside the loop. For count, you just increment it on each iteration. For sum, you add the current value of x into sum. After the loop you print both variables.
$count = 0;
$sum = 0;
for ($x = 3; $x < 100; $x+=3) {
echo $x.", ";
$count++;
$sum+=$x;
}
echo $sum;
echo $count;
add your elements into an array and then use array_sum to sum the array elements , then divide the sum by the count of your array
$arr = [];
for ($x = 3; $x < 100; $x+=3) {
// echo $x.", \n";
$arr[] = $x;
}
print_r(array_sum($arr) / count($arr));
// Output : 51
$i=0;
$tempx=0;
for ($x = 3; $x < 100; $x+=3) {
//total sum
$tempx = $tempx + $x;
//count of how many times the loop ran in this case 33 times
$i++;
}
//first $i was 0 so we add 1
$i=$i + 1;
//getting the average
$average=$tempx / $i;
echo $average;
//output
For the last answer i think we should not do:
//first $i was 0 so we add 1 $i=$i + 1;
Regards

How can I loop through an array, starting at an offset and looping round again?

Newb question: I'm using a foreach loop to get items from an array.
I need to start looping at an offset number- (I'm using a $i variable to do this, no problem).
But when my foreach reaches the end of the array I want it to start going through the array again until it reaches the offset number.
I need to do this so I can have a user open any image in an artist's portfolio and have this image used as the first image presented in a grid of thumbnail icons , with all the other images subsequently populating the rest of the grid.
Any ideas?
Please bear in mind I'm new to PHP! :)
See below for an example of my current code...
$i=0;
$limit=50;// install this in the if conditional with the offset in it (below) to limit the number of thumbnails added to the page.
$offset=$any_arbitrary_link_dependant_integer;
foreach($portfolio_image_array as $k=>$image_obj){//$k = an integer counter, $image_obj = one of the many stored imageObject arrays.
$i++;
if ($i > $offset && $i < $limit) {// ignore all portfolio_array items below the offset number.
if ($img_obj->boolean_test_thing===true) {// OK as a way to test equivalency?
// do something
} else if ($img_obj->boolean_test_thing===false) { // Now add all the non-see_more small thumbnails:
// do something else
} else {
// error handler will go here.
}
} // end of offset conditional
}// end of add boolean_test_thing thumbnails foreach loop.
};// end of add thumbnails loop.
$i = 0;
$limit = 50;
$offset = $any_arbitrary_link_dependant_integer;
$count = count($portfolio_image_array);
foreach($portfolio_image_array as $k=>$image_obj){//$k = an integer counter, $image_obj = one of the many stored imageObject arrays.
$i++;
if ($i > $offset && $i < $limit && $i < ($count - $offset)) {// ignore all portfolio_array items below the offset number.
if ($img_obj->boolean_test_thing===true) {// OK as a way to test equivalency?
// do something
} else if ($img_obj->boolean_test_thing===false) { // Now add all the non-see_more small thumbnails:
// do something else
} else {
// error handler will go here.
}
} // end of offset conditional
}// end of add boolean_test_thing thumbnails foreach loop.
};
Only thing I added was a $count variable.
Edit: If your array starts at 0 I would suggest you put the $i++; at the end of your foreach loop.
A simple method is to use two separate numeric for loops, the first going from offset to end, and the second going from beginning to offset.
<?php
// Create an example array - ignore this line
$example = array(1,2,3,4,5,6);
$offset = 3;
// Standard loop stuff
$count = count($example);
for($i = $offset; $i < $count; $i++)
{
echo $example[$i]."<br />";
}
for($i = 0; $i < $offset; $i++)
{
echo $example[$i]."<br />";
}
?>
This is also almost certainly cheaper than doing multiple checks on every single element in the array, and it expresses exactly what you are trying to do to other programmers who look at this code - including yourself in 2 weeks time.
Edit: depending on the nature of the array, in order to use numeric keys you may first need to do $example = array_values($portfolio_image_array);.
Using Answer Question to force StackOverflow to let me post a decent length of text!
OK #Mark Walet et al, not sure how to post correctly on this forum yet but here goes. I got the issue sorted as follows:
$i=0;
$offset=$image_to_display_number;
$array_length = count($portfolio_image_array);
// FIRST HALF LOOP:
foreach($portfolio_image_array as $k=>$img_obj){// go through array from offset (chosen image) to end.
if ($i >= $offset && $i <= $array_length) {
echo write_thumbnails_fun($type_of_thumbnail, $image_path, $k, $i, $portfolio_image_array, $title, $image_original);
$t_total++;// update thumbnail total count.
}
$i++;
}// end of foreach loop 1.
$looped=true;// Just FYI.
$i=0;// Reset.
// SECOND HALF LOOP:
foreach($portfolio_image_array as $k=>$img_obj){// go through array from beginning to offset.
if ($i < $offset) {
echo write_thumbnails_fun($type_of_thumbnail, $image_path, $k, $i, $portfolio_image_array, $title, $image_original);
}
$i++;
}// end of foreach loop 2.
Thankyou so much for all the help!
:)
as #arkascha suggested use modulo operator
<?php
$example = array(1,2,3,4,5,6);
$count = count($example);
$offset = 3;
for($i = 0; $i < $count; $i++) {
$idx = ($offset + $i) % count
echo $example[$idx]."<br />";
}
?>

Same value counting at end

I have the array:
$array = array(1,1,5,2,3,3,3,3);
I need to find a way to count the amount of times a number is repeated at the end of the array. In this case the number 3 is repeated 4 times.
And if...:
$array = array(1,1,5,2,3,3,3,3,4);
In this case, the result would be 1 because the number 4 only appears once.
Thank you for the help.
Try this: (working example)
$array = array(1,1,5,2,3,3,3,3);
$num = end($array); // this will be 3 - the value to compare to
$count = 0; // init count
for($i = sizeof($array)-1; $i>=0;$i--) // loop from the end backwards
if($array[$i]==$num) // if this is the correct num
$count++; // increase count
else
break; // end loop - not side by side anymore - no reason to keep looping
echo $count; // print the result

Finding the difference between 2 dates and iterating an image based on the difference

Ive managed to loop through a table and get the difference in days between 2 dates adjacent to each other in the table.
Multiple entries have the same date, i have it now that when that date changes, it displays an image however i want it to display the image as many times as the difference in date
$sql = mysql_query("SELECT * FROM Films_Info")
or die(mysql_error());
$last_value = null;
while ($row = mysql_fetch_assoc($sql)) {
if (!is_null($last_value)) {
$a = new DateTime($row['FilmRelease']);
echo "<p>".$row['FilmName']."</p>";
$interval = $a->diff(new DateTime($last_value));
//echo $interval->format('%d days');
$i = 0;
}
$howManydays = $interval->days;
for ( $i; $howManydays; $i++) {
echo "<img src=\"day.jpg\" />";
$howManydays = 0;
}
$last_value = $row['FilmRelease'];
}
for ( $i = 0; $i < $howManydays; $i++) The second is a conditional statement telling when the loop should stop.
The first section in the for loop where it says $i = 0 initialized the variable $i to 0 and then tests the condition $i < $howManydays.
Let's say $howManydays equals 1. That means 0 < 1, so the loop will perform.
At the end of the loop, the third section is called ($i++), so $i is incremented and now equals 1. The second section is called again to test conditions $i < $howManydays which is asking if 1<1 which it's not, so the loop will exit.
So if $howManydays is greater than 0, the loop should happen the integer amount that is in $howManydays.
You will want to remove $howManydays = 0; within the for loop, if you don't want it to only fire once.
The for loop
for ( $i = 0; $i < $howManydays; $i++){
// ...
}
is somewhat equivalent to the while loop:
$i = 0;
while ( $i < $howManydays ){
// ...
$i++;
}
http://php.net/manual/en/control-structures.for.php for more information
In your code above, you should also check if interval was set. You should probably just do an if rather than a while, if only need one interval.
you could just do a simple division on the interval and print out the image that many times
$last_value_u = $last_value->format('U');
$a_u = $a->format('U');
$interval = $a_u - $last_value_u;
$image_count = intval($interval/86400);
for($i=0;$i<$image_count;$i++)
echo "<p><img src=\"day.jpg\" /></p>";
Update
An alternative option would be to loop through the interval:
for($i=$last_value_u;$i<$a_u;)
{
if(intval(($a_u - $i)/86400) == X)
{
// run special code for specific day
}
else
{
// run code for every other day
}
$i+=86400;
}

Empty results when I store records in array, repeat them to reach certain nr and use foreach to display them

This is what my code does:
it gets 4 rows from my table, stores them in an array, repeats them untill they reach 20 inside that array then echo's them whit a foreach loop... problem is i get an empty result at the end of each foreach cycle of the 4 results.
$result = mysql_query("SELECT * FROM ".$table."");
$row_nr = mysql_num_rows($result); // Find out how many rows I have in the table, lets say 4
while($rows = mysql_fetch_assoc($result)){
$arrayrows[] = $rows; // Put my 4 rows in the array
}
// Now I multiply nr. of rows to reach desired number which is 20
$dbRow=0;
for($n=0; $n <= 20; $n++)
{
if($dbRow > $row_nr) $dbRow = 0;
$fullarrayrows[$n] = $arrayrows[$dbRow];
$dbRow++;
}
// after some php pagination code I slice the array:
$arrayslice = array_slice($fullarrayrows, $offset, $rowsperpage);
// Now i display my array
foreach($arrayslice as $slice)
{
echo ''.$slice['name'].'';
echo '<br />';
}
Problem is I get some empty records in the foreach
name1name2name3name4HERE I GET THE EMPTY ENTRYname1name2name3name4AGAIN I GET THE EMPTY ENTRY
... and so on, at the end of each cycle
Thank you very much , please give me an ideea of what's wrong:)
$dbRow indexes start at 0 and end at 3
but $row_nr equals 4
so change this line
if($dbRow > $row_nr) $dbRow = 0;
to
if($dbRow >= $row_nr) $dbRow = 0;

Categories