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;
}
Related
In Python, there exists a Counter class that allows me to do this:
counter = Counter()
counter[2] = 5
counter[3] = 2
for i in range(5):
print(f'counter[{i}]={counter[i]}')
Which will give me the following output:
counter[0]=0
counter[1]=0
counter[2]=5
counter[3]=2
counter[4]=0
Basically it acts as if any element in the dictionary that has not been explicitly initialized has the value of zero, and will never throw an exception when accessing non-existing element.
Is there a similar entity in PHP, or is the only way to check each index when accessing in a loop?
I am looking for a way to avoid doing this:
for ($i = 0; $i < numOfSomeResults; $i++) {
if (isset($otherResult[$i]) {
echo $otherResult[$i];
} else {
echo "0";
}
}
And do something like:
for ($i = 0; $i < $numOfSomeResults; $i++) {
echo $counter[i];
}
Both the indexes and values I need to work with are integers if that helps.
Without reinventing the wheel and following on from Alex's comment, you can use the null coalescing operator (PHP 7+)
for ($i = 0; $i < $numOfSomeResults; $i++) {
echo $counter[$i] ?? 0;
}
Some background information about what it does:
The null Coalescing operator is mainly used to avoid the object function to return a NULL value rather returning a default optimized value. It is used to avoid exception and compiler error as it does not produce E-Notice at the time of execution.
(Condition) ? (Statement1) ? (Statement2);
This same statement can be written as:
if ( isset(Condition) ) {
return Statement1;
} else {
return Statement2;
}
Try this:
Put '$' in front of 'i'. The code below must work.
for ($i = 0; $i < numOfSomeResults; $i++) {
if (isset($otherResult[$i]) {
echo $otherResult[$i];
} else {
echo 0;
}
}
I am using a recursive function in php. The function travers through an array and inputs some values of the array in a new array. I am using array_push() to enter values in the new array and I have also tried to do it without using array_push. This is the part of the function that calls the recursive function
if ($this->input->post('id') != '') {
$id = $this->input->post('id');
global $array_ins;
$k=0;
$data['condition_array'] = $this->array_check($id, $menus['parents'], $k);
// trial
echo "<pre>";
print_r($menus['parents']);
print_r($data['condition_array']);die;
// trial
}
and this here is the recursive function
function array_check($val, $array_main, $k) {
// echo $val . "<br>";
$array_ins[$k] = $val;
echo $k . "<br>";
$k++;
// $array_ins = array_push($array_ins, $val);
echo "<pre>";
print_r($array_ins);
if ($array_main[$val] != '') {
for ($i = 0; $i < sizeof($array_main[$val]); $i++) {
$this->array_check($array_main[$val][$i], $array_main, $k);
}
// $k++;
}
I've been trying to fix this erorr for quite some time with no luck . I would really appreciate any help possible .
thanks in advance
Move the global $array_ins; statement into the function.
Pass the variable $array_ins as a parameter to function
function array_check($val, $array_main, $k,$array_ins) {
}
and call the function
$this->array_check($id, $menus['parents'], $k,$array_ins);
or
function array_check($val, $array_main, $k) {
global $array_ins;
}
usage of global is not recommended in php check it here Are global variables in PHP considered bad practice? If so, why?
The global keyword should be used inside of functions so that the variable will refer to the value in the outer scope.
<?php
$a = 1;
$b = 2;
function Sum()
{
global $a, $b;
$b = $a + $b;
}
Sum();
echo $b; // 3
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++;
}
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;
}
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