0

Here is my php:

<?
  $i = 0;

  function f() {
  $i++;
  echo $i;
  if ($i < 3) {
    return true;
  }
}

while(f())
?>

I was expecting output to be 123

But I get this:

Fatal error: Maximum execution time of 30 seconds exceeded in exp.php on line 5  
3
  • you're not returning false anywhere. Commented Sep 15, 2013 at 22:34
  • not necessary. if nothing is returned, it defaults to null which evaluates to false. However my eyes look for something to return for more readability :) Commented Sep 15, 2013 at 22:36
  • Try $f = function() use($i) {...} and then while($f()) Commented Sep 15, 2013 at 22:39

5 Answers 5

4

$i is not defined in function's scope. Everytime it resets to zero.

$i = 0;

function f() {
    global $i;
    $i++;
    echo $i;
    return $i<3; //thanks @styxxy
}

while (f());
Sign up to request clarification or add additional context in comments.

Comments

1

The $i variable inside your function is a local variable (of that function). If you want to access the variable(s) outside the function, use global. This has to do with the variable scope.

<?php
$i = 0;

function f() {
    global $i;
    $i++;
    echo $i;
    if ($i < 3) return true;
    return false;
}

while(f());

It is also good practice to make sure you return a value on all code paths (and not rely on the the defaults).

4 Comments

This worked, I didn't realize that a locally defined variable would override a global var with the same name, interesting, Thanks.
@andrew Also read about variable scope on php.net ;-).
if ($i < 3) return true; return false; can be shortened to return ($i < 3);
@n.st : yes I know. However, for less experienced people, it's less readable and clear what happens there.
0

$i is a global variable, declared outside of the function. The other $i is a local variable, it has a storage location but no initial value. If you want to refer to the global variable from within the function, add the global keyword...

Comments

0

i is a global variable right? i think you should make it known to the function f().
Like this

global $i;

Comments

-1

Why not just:

$i = 0;

while($i<3){
    $i++;
    f($i);
}

function f($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.