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++;
}
Related
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;
I am taking a demo test at codility.com.
I tried the following PHP test code:
function solution($A) {
$min = 0;
$size = count($A)-1;
for($i=0;$i<5;$i++){
if($i=0)
$min=$A[0];
}
return $min;
}
The script takes around 3.03s to execute where they have set the maximum execution time to 2.00s.
And if i comment the FOR LOOP it works properly.
Any idea ?
You are overwritting your $i variable here:
if($i=0)
it should be
if($i==0)
because you have wirte if($i=0) it is assignment operator not comparision operator. make it correct if($i==0)
function solution($A) {
$min = 0;
$size = count($A)-1;
for($i=0;$i<5;$i++){
if($i==0)
$min=$A[0];
}
return $min;
}
Your for loop looks like this:
for($i = 0; $i < 5; $i++)
This means: initialize $i to 0, and until $i is 5 or more, execute the loop and increment $i.
But, you wrote this:
if($i = 0)
To compare $i and 0, you should've used ==, not =. This sets $i to 0. The if is not executed, as 0 is equal to false. Then $i is incremented to 1. 1 is less than 5, so the loop is executed forever.
Use if($i == 0) to fix it.
There is a mistake that everyone has pointed out which is if($i=0) should be if($i==0).
But I have one concern. Why there is a for loop when it is simply returning $min which is $A[0] ?
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 />";
}
?>
i have a set of fields say field1, field2,... field10.
i pass this value from one page to another and get the value using post method inside a for loop as follows..
for ( $i = 1; $i <= 10; $i++) {
$txtfield.$i = $_POST[field.$i];
echo $txtfield.$i;
}
This makes an infinite loop printing the value of field1 continuously..
Finally this error occurs..
Fatal error: Maximum execution time of 60 seconds exceeded in C:\xampp\htdocs\...
what is the mistake in this code???
I don't know what is the value "field", shouldn't it be a variable with a $?
Anyway, I think you wanted to do this:
for ( $i = 1; $i <= 10; $i ++) {
$varname = ($txtfield . $i);
$$varname = $_POST[field.$i];
echo $$varname;
}
You're reassigning $i here each time to $_POST[field.$i]
$txtfield.$i = $_POST[field.$i]
Kind of like this, with the second line being a non-expression:
$i = $_POST[field.$i];
$txtfield.$i;
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;