I have this code.
$add = (function () {
$counter = 0;
return function () use(&$counter) {return $counter += 1;};
})();
echo $add(); //1
echo $add(); //2
echo $add(); //3
Expected Output:
111
Original Output:
123
Inside the function $counter=0 is assigned by 0 so the &$counter should be 0.
So when i called it second time it sees $counter=0 and so that &$counter will be 0, Isn't it?
Why it is incrementing?
It does not call $counter=0 for the second time. You call it just once when initiating the first function. When you call $add(), you call every time the second function (that is in your return statement) which just uses the modified value of $counter that you passed by reference. If you would add echo $counter; after the $counter = 0; you will see that.
What do you mean by "sees"? The first time you execute $add(), the inner counter is counted up. As you used a reference pointer (through adding the ampersand in use(&$counter)) to the original $counter, this is also manipulated, so after executing this once, the counter variable no longer contains a zero.
When you remove that ampersand, the innermost function uses a fresh counter each and every time, such that your expected output is met
Because you pass a reference to the function the initial $counter = 0; value is also increased each time you add 1 to it using $counter += 1; that's why your result is "123".
To get "111" you need to pass a variable to a function $counter, not a reference.
Related
I am learning about static variables in PHP and came across this code in PHP manual.
<?php
function test() {
static $count = 0;
$count++;
echo $count;
if ($count < 10) {
test();
}
$count--;
}
?>
I couldn't understand the purpose of last $count--;. So, I wrote a different version of the function below:
<?php
function test() {
static $count = 0;
$count++;
echo $count;
if ($count < 10) {
test();
}
echo 'I am here!';
$count--;
}
test();
?>
The output of above code is:
12345678910I am here!I am here!I am here!I am here!I am here!I am here!I am here!I am here!I am here!I am here!
Why isn't the output just the line below because we go past the if condition only once.
12345678910I am here!
If we are going past the if condition multiple times, then shouldn't the output be:
1I am here!2I am here!3I am here!4I am here!5I am here!6I am here!7I am here!8I am here!9I am here!10I am here!
Thanks.
This is more about recursion than static variables. However:
Why the numbers are written out first and the text afterwards? Let's break each run of the function. For simplification, I'll only use example with 2 calls (if ($count < 2))
1st call starts, $count is incremented to 1
prints 1
Within the 1st call, the condition $count < 2 is met, so it calls test() (so that's going to be the 2nd call)
2nd call starts, $count is incremented to 2 (if it weren't static, it wouldn't keep the value from the higher scope)
prints 2
Within the 2nd call, the condition $count < 2 is NOT met, so it skips the if block
prints I am here! and ends the 2nd call
Now the 1st call is done running the recursive function so it continues
prints I am here! and ends the 1st call
When you're calling test() within the method that doesn't stop the execution of the rest of the code in the method.
The reason, as far as i can see, it doesn't output a number after each string of "i am here" is because you're calling the method test() before the output. So each time it's waiting for that method to complete before moving on to the next string.
If you were to move the $count echo to after it I believe it'd output as expected.
Does that answer your question at all?
I have a function in a codeigniter controller that calls a model function with 3 parameters. Of the 3 passed parameters, response_num comes across blank when it should be an integer value.
Hoping someone else's eyes can spot the trouble!
Thanks! (I'm still learning php and codigniter).
Here is the calling function in the controller:
for($i=1; $i < $possible_results_count; $i++) {
print_r("iteration: ".$i);
$g1 = $this->Response_model->get_possible_results_for_response($i, $this->session->userdata("assess_id"), $this->session->userdata("user_id"));
print_r("Sum for ".$i."=".$g1["response_value"]);
if($g1["response_value"] >= $sensitivity) {
$results[$i] = $userdata["possible_results"][$i]; //
$result_count++;
// print_r("added [".$userdata["results"][$i]."]");
}
$total_results = $result_count;
if ($total_results >= $min_result_count) {
// print_r("found 3 gifts-breaking for loop");
break;
}
}
The called function in the model:
public function get_possible_results_for_response($*response_num*=FALSE, $assess_id, $registrant_id){
print_r("response_num=".$response_num."; assess_id=".$assess_id."; registrant_id=".$registrant_id);
$i is the variable in the calling functions for loop.
the print_r's show all variables are correct except for the parameter that was passed as $i, it is blank.
$i tracks the iteration count and passes it to the model for a db lookup using $i to determine which record to use in calculations.
Solved!!!
duh!!! Right after I posted this question, I decided to initialize $i ($i=0) just before the for loop and it worked, the value was passed to the calling function. Apparently using $i in the for loop without initializing works for the for loop, but not as a regular variable unless it is initialized.
Live and Learn :)
I have to do a function that returns a string at contrary to another variable. I have a problem.
<?php
$parolaAlContrario="";
function ribaltaStringa($nome){
$lenght=strlen($nome);
for($i=0;$i<$lenght+4;$i++){
$parolaAlContrario[$i]=$nome[$lenght-1];
$lenght=$lenght-1;
}
echo implode($parolaAlContrario);
}
ribaltaStringa("marco"); ?>
This code returns 'ocram'. I don't understand why if I put implode($parolaAlContrario) outside the function the result is the variable $parolaAlContrario empty. Why?
This is because the scope of your variable is outside of your function. You need to assign the variable to whatever the result is from the function.
You should make your function return the variable, and assign it when complete.
function ribaltaStringa($nome)
{
$lenght = strlen($nome);
$parolaAlContrario = array();
for($i = 0; $i < $lenght + 4; $i++) {
$parolaAlContrario[$i] = $nome[$lenght - 1];
$lenght = $lenght - 1;
}
return implode($parolaAlContrario);
}
Notice, instead of echoing the variable, I return the variable. This allows us to assign the result to your variable once the function is finished.
I've also defined the variable $parolaAlContrario inside the function right outside the loop, this will allow you to return the value.
When you call the function, you should assign the variable again.
$parolaAlContrario = ribaltaStringa("marco");
Likewise, you could make a completely new variable with the word reversed by just changing the name of the variable during declaration; E.G:
$newVariable = ribaltaStringa("marco");
Why make it simple if you can make it complicated? You don't need to write your own function for that. Just use PHP's built-in function strrev() which reverses a string and you can save it to a new variable if you want:
$parolaAlContrario = strrev('marco');
Try it out:
https://3v4l.org/RmdE1
I need a variable to be passed along several functions & if statements, i'm going to keep it short.
I start off with initializing a static counter which i will use to keep track of the case number in my mysql database;
static $counter = 1;
then i write my function in which i try to simply increment my global variable (this is in an if statement inside my function);
$counter++;
Now my code compiles and runs perfectly but the counter seems to never increment and give every case id 1.
Anyone know how i managed to mess this up?
EDIT (Current structure):
<?php
static $counter = 1;
function frontend($connection){
global $counter;
(...)
if(isset($_POST['submit'])){
(...)
if(isset($_POST['betaald'])){
$counter++;
}
}
} ...
Now this code makes a neat database of all i need except the counter which seems to be unchangeable.
Explain more about your code and see the example.
<?php
function keep_track() {
STATIC $count = 0;
$count++;
print $count;
print "<br />";
}
keep_track();
keep_track();
keep_track();
?>
This will produce the following result −
1
2
3
These function statements are confusing me.
I'm new to php, help me to understand these functions:
function addFive($num)
{
$num += 5;
}
function addSix(&$num)
{
$num += 6;
}
$orignum = 10;
addFive( $orignum );
echo "Original Value is $orignum<br />";
addSix( $orignum );
echo "Original Value is $orignum<br />";
first echo outputs 10
Second echo outputs 16
What is the difference between these 2 functions?
There are two types of call:
1) Call by value: addFive($num)
2) Call by reference: addSix(&$num)
In first case, you are just passing value of the variable.
Hence, only value gets modified keeping original variable untouched.
In second case, you are passing reference to the variable, hence the original value gets modified.
The first function passes the argument by value - in other words, it's copied into the function, and any change you perform on it will be on the local copy.
The second function passes the argument by reference (note the & before it in the function's signature). This means the variable itself is passed, and any modification you perform on it will survive beyond the function's scope.
& is used to pass address of an variable in second function declaration "addSix(&$num) {}"
In second function while calling addSix( $orignum ); updation of value is done on address of "$orignum"
whereas in first function updation is done on "$num"
First function add 5 to your number and second adds 6 to your number
$num+=6 means $num= $num+6
And first function works on Call by value and second function works on Call by reference