counting results within a if/else statement - php

I am trying to sum the total results in an if/else statement. so the $result (in there for example) would appear 4 times. I have tried count($result), this doesnt work.
while ($sq=mysql_fetch_array($query)){
if ($avg > $btmspeed && $avg < $topspeed){
$result;
}else{
}
}
Basically I am running a while loop through some database results and these existing variables would give 4 results through the if statement and I want to reflect that. I know its probably and easy answer but banging head against a wall and search engines havent given me the answer. please help!

Use a counter.
Var i=1;
Outside of the loop.
Inside the loop add:
i++;

Do you just need to move the $result declaration outside the loop and increment it inside the 'if' block?
$result = 0
# loop starts here
if ($avg > $btmspeed && $avg < $topspeed){
$result = $result + 1
} else{
}

Assuming your result is a number. You would loop over whatever it is I assume an array with information, where you'd be checking the if-else like you originally provided.
$i = 0;
for($x=0; $x < $result; $x++;)
{
if ($avg > $btmspeed && $avg < $topspeed){
$i++;
}else{
}
}
echo $i;

Related

PHP Is it possible to skip two or more iterations?

I am aware we can skip the next iteration with continue in a for loop. Anyway to skip the next x loops (2 or more)?
You actually can't, you can do a dirty trick like
for ($i=0; $i<99; $i++){
if(someCondition) {
$i = $i + N; // This will sum N+1 because of the $i++ in the for iterator (that fire when the new loop starts)
continue;
}
}
If you're iterating with a for loop (as opposed to a foreach loop) you could do something like this:
for ($i=0; $i<$numLoops; $i++) {
if(condition()) {
$i+= $numLoopsToSkip;
continue;
}
}
Take for example, you can define the amount of times you want to loop as you want as $y
<?php
y = 5;
while (true) {
// do something
if (y > 0) {
y--;
continue;
}
// do something else
}
?>
Coming soon in PHP 'X' ;-)
continue += x;

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 />";
}
?>

While Loops and Multiple Conditions

Is it possible to write multiple conditions in a while loop? If not, what is an alternative? I tried it and was returned with an error relating the line of code that sets up the conditions for the while loop. Here is an example of what I mean.
$s = 1;
while ($result_row = mysql_fetch_assoc($query) && $s < 5)
{
echo $result_row['id'];
$s++;
}
That is possible, but because = has lower precedence than && you need parentheses to ensure that your statement is interpreted correctly:
while (($result_row = mysql_fetch_assoc($query)) && ($s < 5))
The parentheses around $s < 5 are not required here, but I've included them for clarity.
However it would be easier just to modify your query to only return 5 rows, by adding LIMIT 5.
SELECT ...
FROM yourtable
ORDER BY ...
LIMIT 5
You could try:
$s=1
while ($result_row = mysql_fetch_assoc($query))
{
echo $result_row['id'];
$s++;
if($s>5){
break;
}
}
http://php.net/manual/en/control-structures.break.php
while i see nothing wrong in that. the other way round is to do something like this.
$s = 1;
while ($result_row = mysql_fetch_assoc($query))
{
if($s < 5) {
//enter the condition
}
$s++;
}
The value of $result_row is probably being set to the Boolean condition of whether mysql_fetch_assoc($query) returns something true-ish and $s is less than 5. So trying to read $result_row as a dictionary no longer works.
You can use parenthesis to specify exactly how things get parsed:
while (($result_row = mysql_fetch_assoc($query)) && ($s < 5))
This way, $result_row gets set to mysql_fetch_assoc($query), which is what you want, and the loop continues as long as the logical value of that assignment returns something true-ish, as well as s is less than 5.

If statement getting hung up

I have a while loop that contains an if statement. The while loop works fine but when I run the following if statement for each value passed through the while loop, and the if statement returns true, the script hangs up and I get the 30 second maximum execution time error.
I am not sure if it is creating an infinite loop or what. Can anyone spot the problem?
$size = count($_POST['itemname']);
// start a loop in order to update each record
$i = 0;
while ($i < $size) {
// define each variable
$itemname= $_POST['itemname'][$i];
$id = $_POST["id"][$i];
if(preg_match('/[A-Za-z]/',$itemname)) {
echo("has words");
} else {
//update code here
}
}
You never increment $i, that is what is hanging it up as it will always be < $size
while ($i < $size) { // changed this to >
// define each variable
$itemname= $_POST['itemname'][$i];
$id = $_POST["id"][$i];
$i++; // increment $i
You never increment $i. Try a for loop instead; they're a little more explicit.
You need to increment $i somewhere outside of the if statement.
you never change $i in the while loop
you have to increment $i for each loop or else if its true once it will always pass
add $i++ between the last 2
}
}
so it looks
}
$i++;
}

How to increase number of iterations from within the loop in php?

I'm working on custom pagination system and encountered following problem. When one of the elements is filtered out of the set, the size of the final array is smaller than needed. Therefore I'm looking for a solution to increase the number of iterations from within the loop to always get array consisting of 50 elements.
$limit = 50; //Number of elements I want to fetch
for($x=0; $x<$limit; $x++){
if ($elementIsNotFiltered) {
//add element to $someArray;
}
else {
//increase the number of iterations, so even if some elements are filtered out,
//the size of $someArray will always be 50
}
}
Thanks for any help.
Do it in a while() loop instead, and break when you finally hit your $limit
Use a while loop.
while(count($somearray) < 50 && /*elements remain*/) ...
else {
++$limit;
}
Tried that?
You may also do the same thing the other way round:
else {
--$x;
}
Or be a little bit more effective:
$x = 0;
while ($x != 50) {
if ($notFiltered) {
++$x;
}
}
If you want to save the counter variable, too, you may use:
while (!isset($array[49])) {
}
The !isset($array[49]) here is only a synonym of count($array) < 50.
It sounds to me like you're looking for a while loop - not a for loop:
while ($items < 50 && [more items to filter]) {
if ([add to array]) {
$items++;
}
}
If you really want to do it in your for loop you can always modify $x but this makes your code unreadable and hard to maintain - I would recommend not doing this...

Categories