I'm trying to learn about static variables inside a function. So I created this:
<?php
// Create a function that has a counter
function counter_inside_function()
{
static $counter = 0;
++$counter;
return $counter;
}
// counter_inside_function() in a variable
$counter_function = counter_inside_function();
// Create a loop and place the function inside it
$count = 1;
while ($count < 11) {
echo $counter_function, '<br>';
// echo counter_inside_function(), '<br>';
$count++;
}
I was expecting to increment the counter but it didn't. However, if I uncomment line 21 and echo the function directly (not the $counter_function variable, that's when it incremented. What I don't get is it started counting from 2 instead of 1. But when I removed $counter_function = counter_inside_function(); I got the result I wanted.
You should move $counter_function = counter_inside_function(); inside your while loop so that the function is called on every iteration:
<?php
// Create a function that has a counter
function counter_inside_function()
{
static $counter = 0;
++$counter;
return $counter;
}
// Create a loop and place the function inside it
$count = 1;
while ($count < 11) {
$counter_function = counter_inside_function();
echo $counter_function, '<br>';
$count++;
}
When you call the function counter_inside_function() on line 13 and stored its return value into a variable what you've done is you've run that function one time and its returning 1. Now since the variable in counter_inside_function() is static its going to keep that value the next time you call it. That's why it seems as if its starting at 2 when really you've incremented it to 1 before the while loop and then during the loop it seems as though it is starting at 2.
Now the issue with the loop is that you echoing the variable $counter_function 20 times does not mean you're calling the function counter_inside_function() 20 times. All you're doing is taking the number that was stored in it the first call (which is 1) and echoing it out 20 times. So if you remove the comment on line 21 and remove the function call on line 13 (so that it doesn't increment to 1 before your loop begins) your program will give you the results you want.
This is how your code should look like:
// Create a function that has a counter
function counter_inside_function()
{
static $counter = 0;
++$counter;
return $counter;
}
// Create a loop and place the function inside it
$count = 1;
while ($count < 11) {
$counter_function = counter_inside_function();
echo $counter_function, '<br>';
$count++;
}
Related
This question already has answers here:
How to use return inside a recursive function in PHP
(4 answers)
Closed 9 months ago.
I'd like to return some value using a recursive function. Unfortunately the function doesn't return anything until I change return to echo.
Here is a similar function I created for better understanding.
function debug($a, $i) {
$a .= $i;
if ($i !== 5) {
$i++;
debug('echo', $i);
} else {
return $a; // expecting echo5 (echo works perfectly)
}
}
echo debug('echo', 0); // doesn't return anything
Just return the value from the recursive call in order to catch the result.
EDIT:
Here is a new way of handling your code.
If the number you are passing is greater than five then subtract 1
every recursive call.
If the number is lower than five than add 1 every recursive call.
Otherwise it returns 5.
So when it reaches five, the output will be for example echo012345 or echo98765.
If you want to limit the output to echo5, then you should wrap $a .= $i with an if statement to check if ($i == 5).
<?php
function debug($a, $i) {
$a .= $i;
if ($i > 5) {
$i--;
return debug($a, $i);
} elseif ($i < 5) {
$i++;
return debug($a, $i);
}
return $a;
}
echo debug('echo', 10);
?>
The function is working 100% as intended. You do not print the value simply because the function is "returning" it. If you want the value printed, then you must echo it as you've observed yourself.
Think of it this way:
Return - returns the value in raw data.
echo - prints stuff.
Also the way your recursive function works now, it only contains the return value within its scope, so the value is "dropped" when the execution is completed. That's why you won't be able to echo anything. When you echo inside the function, it's echoing the value before stopping the execution.
One way to circumvent this, is by adding a print parameter to the function if you wish for your value to be printed,
Example:
function debug($a, $i, $print=false) {
$a .= $i;
if($i < 5) {
$i++;
debug('echo', $i, $print);
} else{
if($print){
echo $a;
}
return $a;
}
}
debug('echo', 0, true);
I'm trying to read the whole file using fgetc() with a do..while loop. I know this is not recommended but it should work. The contents of counter.dat are i dont know whta to do but the ouput that I'm getting is 0. Why 0?
<?php
$f = "counter.dat";
if (!($fp = fopen($f,"r"))) {
die("Can Not Open $f");
}
do {
$one_char = fgetc($fp);
$counter = $one_char;
$counter .= $one_char;
} while($one_char);
fclose($fp);
$counter = (int) $counter;
echo $counter;
?>
You're overwriting $counter each time through the loop, before you append to it. And on the last iteration, $one_char will be FALSE, so you're setting $counter = FALSE;, and converting that to an integer returns 0.
You also need to initialize $counter to an empty string at the beginning.
Since the file doesn't contain an integer, you shouldn't use (int) $counter. Just print the value of $counter.
Do it like this:
$counter = "";
while ($one_char = fgetc($fp)) {
$counter .= $one_char;
}
echo $counter;
This exits the loop immediately when it gets to EOF, it won't try to use the FALSE value from the last iteration.
I want to check if a static variable has been declared/initialized previously, e.g. if a function with a static variable is being run for the first time. See the following example code:
function init_i (){
// check if $i is set??
if(isset($i)) echo '$i is static and is set ';
static $i=0;
$i++;
echo "$i<br>";
}
function run_init(){
init_i();
}
run_init(); //output 1
run_init(); //should output $i is static and is set 2
run_init(); //should output $i is static and is set 3
run_init(); //should output $i is static and is set 4
run_init(); //should output $i is static and is set 5
The problem is that isset($i) never seems to prove true even though it is a static variable. How do I check static $i has already been set?
Just omit out the default value, and it will be null:
static $i;
// check if $i is set??
if(isset($i)){
echo '$i is static and is set ';
}else{
// first call, initialize...
$i = 0;
}
...
isset() returns TRUE if variable is set and not null.
I don't get what's your reasoning behind this, because you can just check the value is the initial value (0) and you know that's the first call...
you can do
function init_i (){
static $i=0;
// check if $i is set??
if ( $i != 0 )
echo '$i is static and is set ';
$i++;
echo "$i<br>";
}
check the condition after declared the static variable
static $i=0;
if(isset($i)){
echo '$i is static and is set ';
}else{
$i=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
$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());
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).
$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...
i is a global variable right?
i think you should make it known to the function f().
Like this
global $i;
Why not just:
$i = 0;
while($i<3){
$i++;
f($i);
}
function f($i){
echo $i;
}
i have a very simple question. How can i make this code
$i = 0;
foreach($Array as $Value)
{
echo $i;
$i++
}
but written like this?
foreach($Array as $Value)
{
$i = 0;
echo $i;
$i++
}
should i use a STATIC variable? or what? I don't have a clear view on this.
Thank you!
You shouldn't really do that. static variables are used to persist a variable's value between invocations of the function they're embedded in. They're not useful for a simple loop. Your second code will simply reset the counter to zero on every iteration.
e.g. this is a correct usage:
function count() {
static $x = 0; // executed the first time count() is called, then never again"
echo ++$x;
}
count(); // 1
count(); // 2
count(); // 3
You can certainly have
foreach($array as $val) {
static $x = 0;
echo ++$x;
}
but you don't gain anything, since that particular piece of code never goes out of scope for the duration of the loop, so $x's value would never get "lost".
you may want use
foreach($Array as $i => $Value)
{
echo $i;
}
or
foreach(array_values($Array) as $i=>$Value)
{
echo $i;
}
While first your example is correct, too