PHP post method inside for loop causes infinite loop - php

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;

Related

Can I assign same variable for multiple loop

Case 1 loop inside another loop Can I assign both the $i variable for incrementing?
for($i=0; $i < 10; $i++)
{
for($i=0; $i < 5; $i++)
{
echo "You are too cute";
}
}
Case 2 : if it's not inside, Could I declare $i for both?
like this
for($i=0; $i < 10; $i++)
{
}
for($i=0; $i < 5; $i++)
{
}
There are already some answers that are just fine, but here's a slightly different perspective.
It depends on what you mean by "can". You can do this in the sense that it is syntactically correct PHP code.
for($i=0; $i < 10; $i++)
{
for($i=0; $i < 5; $i++)
{
echo "You will never see this text in your browser.";
}
}
But because a loop does not introduce a new variable scope in PHP, it creates an infinite loop.
The outer loop will execute once, then the inner loop will reset $i to 0, increment it to 5, return control to the outer loop, which will execute once, immediately causing the inner loop to start again, resetting $i to 0 and incrementing it to 5, and so on, forever (at least until your script times out). The outer loop can never end because the inner loop affects $i so that it can never satisfy the exit condition of the outer loop.
In other words, just use a different variable for the inner loop. Removing one integer variable is not going to be a noticeable optimization of your code, if that's what you're concerned about.
In the second example, there's no reason not to reuse $i.
Case 1: It will you get a really odd result, check it out here
How to do it properly? Check that out here
for($i=0; $i < 10; $i++){
for($k=0; $k < 5; $k++){
echo "1)".$i." 2)".$k."\n";
}
echo "\n";
}
Case 2: Works fine as stated in above comments and other answer. But, may I also add that in for instance this example.
for($i=0; $i < 10; $i++){
echo $i."\n";
}
echo "\n Outside the loop: ".$i." \n";
for($i=0; $i < 5; $i++){
echo $i."\n";
}
You can acces $i still after the loop has happend. The reason why you can use $i again is because you are declaring it $i =0; again, without interest toward another loop that is currently running (as is happening in case 1).
You can test this example here
Case 1 : No, you cant. you need to create variable individually for each loop.
for($i=0; $i < 10; $i++)
{
for($j=0; $j < 5; $j++)
{
echo "You are too cute";
}
}
Case 2 : Yes you can.
for($i=0; $i < 10; $i++)
{
echo "You are too cute";
}
for($i=0; $i < 5; $i++)
{
echo "You are too cute";
}
Case 1:
Short answer No you can't .
Long Answer .
First you need to understand what actually a variable is and How that Loop actually works .
Each and every variably is actually a reference to memory. In you example you have created a variable named $i and it can't be greater or equal 10 after incrementing value by one.
In the machine level it is translated to an address in the memory. say for example $i points to a random address 0xF25 When ever you loop it and incrementing it, the next address becomes 0xF30.
When ever you write a for loop, compiler automatically assigns a fixed memory address and that address it limited to your variable scope.
What compiler does is, it creates a table for that token($i). In simple form Look below an example
$i(This is the token ) -> 0xF25 (This is the value)
This value is updated when you do $i++
In nested Loop compiler assigns same table(though outer loop cant access inner loop variables). If compiler puts same variable for inner loop, it will be contradictory. Because inner loop may start from memory address 0xE21. In that case when your outer loop increment value by One it will be 0xE22 but as discussed above it needs to be 0xF30 .
That is why compiler does not allow this and we need to use CASE 2 example.

How to I increment a single element in an array?

I have the PHP code below:
<?php
$length = $_GET["length"];
$maxValue = $_GET["maxValue"];
$distribution = array();
for($j = 0; $j < $maxValue; $j++) {
$distribution[j] = 5;
}
$x = 0;
$x++;
for($j = 0; $j < $maxValue; $j++) {
echo $distribution[j] , " ";
}
echo $x;
?>
$x starts as 0 and is incremented by 1. However, just below $x is incremented, I am also incrementing the first element of the "distribution" array - $distribution[0]. And it's not working. It worked fine when I was initializing the elements (set them to 5).
Any ideas on why it might now be working? I am probably referencing the array element wrong. But this seems inconsistent.
When you say $distribution[j] -> php doesn't understand the j as a variable - but rather as an undefined constant
It looks like you are trying to say $distribution[$j] - which is partially -why your increments aren't working - -
The other reason would be that you aren't ever calling $distribution[$j]++ --- so there is no incrementation happening...

For LOOP taking time to execute in PHP

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] ?

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++;
}

What's the difference between ++$i and $i++ in PHP?

What's the difference between ++$i and $i++ in PHP?
++$i is pre-increment whilst $i++ post-increment.
pre-increment: increment variable i first and then de-reference.
post-increment: de-reference and then increment i
"Take advantage of the fact that PHP
allows you to post-increment ($i++)
and pre-increment (++$i). The meaning
is the same as long as you are not
writing anything like $j = $i++,
however pre-incrementing is almost 10%
faster, which means that you should
switch from post- to pre-incrementing
when you have the opportunity,
especially in tight loops and
especially if you're pedantic about
micro-optimisations!"
- TuxRadar
For further clarification, post-incrementation in PHP has been documented as storing a temporary variable which attributes to this 10% overhead vs. pre-incrementation.
++$i increments $i, but evaluates to the value of $i+1
$i++ increments $i, but evaluates to the old value of $i.
Here's an example:
$i = 10;
$a = $i++;
// Now $a is 10, and $i is 11
$i = 10;
$a = ++$i;
// Now $a is 11, and $i is 11
There is sometimes a slight preformance cost for using $i++. See, when you do something like
$a = $i++;
You're really doing this:
$temporary_variable = $i;
$i=$i+1;
$a=$temporary_variable;
++$i is pre-incrementation
$i is incremented
the new value is returned
$i++ is post-incrementation
the value of $i copied to an internal temporary variable
$i is incremented
the internal copy of the old value of $i is returned
++$i //first increment $i then run line
$i++ //first run line then increment $i
this example elplains simply
<?php
$x = 10;
echo $x++. ' '.$x; // the result is 10 and 11
echo '<br>';
$y = 10;
echo ++$y. ' ' .$y; // the result is 11 and 11
// so the $x++ is not showing +1 at first but the next time
// and the ++y is showing +1 first time but not increasing next
in this case there is no difference:
for($i = 0;$i<3;++$i)var_dump $i;
/*
int(0)
int(1)
int(2)
*/
for($i = 0;$i<3;$i++)var_dump $i;
/*
int(0)
int(1)
int(2)
*/
but:
for($i = 0;$i<3; $j = ++$i )var_dump($j);
/*
NULL
int(1)
int(2)
*/
for($i = 0;$i<3; $j = $i++ )var_dump($j);
/*
NULL
int(0)
int(1)
*/
Difference is: ++$i will increment $i variable and return updated value, while $i++ will return original value, so increment it.
$prefix = 1;
$postfix = 1;
echo ++$prefix; // 2
echo $postfix++; // 1
To explain jldupont's point:
$i = 1;
$x = $i++;
echo $x; // prints 1
$x = ++$i;
echo $x; // prints 3
Another way of looking at pre and post incrementing is that it's shorthand for combining 2 statements.
Pre-incrementing
// long form
$y = $y + 1;
$x = $y; // any statement using $y
// shorthand
$x = ++$y; // the same statement using $y
Post-incrementing
// long form
$x = $y; // any statement using $y
$y = $y + 1;
// shorthand
$x = $y++; // the same statement using $y
$i++ is known as post-increment. It increments the value of $i only after assigning the original value of $i to $j first.
++$i is known as pre-increment. It increments the value of $i before assigning the value to $j, so the updated value of $i will be assigned to $j.
Hence,
$i = 4;
$j = $i++;
// Now, $i = 5 and $j = 4
$i = 4;
$j = ++$i;
// Now, $i = 5 and $j = 5
These theories apply in a similar manner for decrementing as well.
Hope this helps!
It's probably best-illustrated by an example...
Post-increment:
$zero = 0;
$n = $zero++; //$n is zero
Pre-increment:
$zero = 0;
$n = ++$zero; //$n is one
Short answer:
Prefix increases the value and returns the value increased
Postfix increases the value and returns the value before it was increased
Prefix is faster
Long answer: If you think a little about it, how you would implement those yourself, you will probably realize why prefix is faster. Truth to be told, postfix is actually (often) implemented using prefix:
const T T::operator ++ (int) // postfix
{
T orig(*this);
++(*this); // call prefix operator
return (orig);
}
Avoid postfix unless you have a specific reason not to. The difference in speed can be quite a lot for complex datatypes.
I actually looked this up a few days ago. Heres my source.
The main purpose of the post-fix increment operator is usage like this:
while(*condition*)
$array[$i++] = $something;
This is a very elegant way, how to get around some array iterations.
Breakdown:
Variable $something will be assigned to the array element indexed with $i
Variable $i will be incremented
Iteration is at the end, condition will be checked
In all other cases, you should use the prefix operator. It makes the code much more clear (You can be sure, that you already work with the incremented value of particular variable).
I ran the following code to test if ++$i is 10% faster than $i++. I admit, the code does not have a stable outcome but even then I should at least have seen some numbers near the 10%. The highest I got was 4-4.5% approximately.
<?php
$randomFloat = rand(0, 10) / 10;
$before1 = microtime(true);
for($i=0; $i <1000000; ++$i){
$rand = (rand(0, 10) / 10) * (rand(0, 10) / 10);
}
$after1 = microtime(true);
echo 'it took '.($after1-$before1) . ' seconds fot ++$i<br />';
$before2 = microtime(true);
for($i=0; $i <1000000; $i++){
$rand = (rand(0, 10) / 10) * (rand(0, 10) / 10);
}
$after2 = microtime(true);
echo 'it took '.($after2-$before2) . ' seconds fot $i++<br /><br />';
echo '++$i is '.((($after1-$before1)*100)/($after2-$before2)-100).'% faster than $i++';
Both operators still do what their syntax implies: to increment. Regardless of prefix or postfix, the variable is sure to be incremented by 1. The difference between the two lies in their return values.
1. The prefix increment returns the value of a variable after it has been incremented.
2. On the other hand, the more commonly used postfix increment returns the value of a variable before it has been incremented.
// Prefix increment
let prefix = 1;
console.log(++prefix); // 2
console.log(prefix); // 2
// Postfix increment
let postfix = 1;
console.log(postfix++); // 1
console.log(postfix); // 2
To remember this rule, I think about the syntax of the two. When one types in the prefix increment, one says ++x. The position of the ++ is important here. Saying ++x means to increment (++) first then return the value of x, thus we have ++x. The postfix increment works conversely. Saying x++ means to return the value of x first then increment (++) it after, thus x++.

Categories