0

Here is my php code given below when I run it in my browser its display 1 continuously. My question is why its show like this? After execution its displays a fatal error : maximum execution time is exceeded. what is that?

    <?php
        for ($i=1; $i<=5; $i+1) { 
            echo $i." ";
        }
    ?>

Give me proper answer. Make me sure that what is the execution time of php code? TIA

3
  • Is $i+1 a legal construct in the language? Most interpreters just print garbage for that code. Commented Oct 21, 2017 at 13:57
  • That is a silly mistake. just have a look at the below answers, But to answer the final point, its up-to you that whats the time limit that you had chosen. you can set the script execution time as : ini_set('max_execution_time', 300); Commented Oct 21, 2017 at 13:58
  • use for ($i=1; $i<=5; $i++) Commented Oct 21, 2017 at 15:04

9 Answers 9

4

$i+1 does not increment the value of $i. It only adds 1 to what is in $i but it does not assign it back to $i. Your loop does this:

$i = 1
while ($i<=5) { 
    echo $i." ";

    $i+1;
}

$i+1 on it's own doesn't do anything.

You need something like $i = $i + 1. Or for short $i += 1. Or even shorter and better: $i++.

for ($i=1; $i<=5; $i++) { 
    echo $i . " ";
}
Sign up to request clarification or add additional context in comments.

Comments

1

It is because of $i+1 in for loop. This is basically an expression and it produces a result but you never assign this result to $i. Therefore you would rather do something like $i = $i + 1 or, in real life, use incrementation $i++. So the final code will looks like:

for ($i = 1; $i <= 5; $i++) {
  echo $i." ";
}

Comments

1

use $i++ not $i+1, $i++ is $i=$i+1

Comments

0

Change your code to

<?php
for ($i=1; $i<=5; $i++) { 
echo $i." ";
}
?>

because first you must set value for $i

Comments

0

You need to do

<?php
    for( $i = 1; $i <= 5; $i++) { 
      echo $i." ";
    }
?>

Now you just say 1 + 1 but you don't assign it to anything. You could use $i = $i + 1 but it's the same as $i++

Comments

0
<?php
    for ($i=1; $i<=5; $i++) { 
      echo $i." ";
    }
?>

Comments

0

in a for loop, every turn you need to increase value of $i. but you forgot to increase value of $i. You wrote $i +1 but it needs to be assigned with new value of $i.

In short, you should change $i +1 to $i = $i +1 or $i ++

the right code:

<?php
for ($i=1; $i<=5; $i = $i+1) { 
echo $i." ";
}
?>

Comments

0

You are not changing the value of $i in the loop. Either $i =$i +1 or $i++ instead of $i + 1 will do.

Comments

-1

You've problem in printing the line. It should look like

<?php
   for ($i=1; $i<=5; $i++) { 
   echo $i;
   }
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.