Unable to understand the working of PHP recursive function [duplicate] - php

This question already has answers here:
Understanding recursion [closed]
(20 answers)
Closed 4 years ago.
I find it difficult to understand the working of this recursive function in PHP. I am not able to follow the code written at return statement. How the total of numbers from 1 to 10 is added? I eagerly want to understand this line return $count + sum($count + 1);
My whole code is:
<?php
function sum($count)
{
if($count <= 10)
{
echo $count;
echo "<br />";
return $count + sum($count + 1);
}
}
$result = sum(1);
echo "The total is $result";
?>
Output:
1
2
3
4
5
6
7
8
9
10
The total is 55
How the total 55 is received in my code? I want to learn it step by step.

Define the function
function sum($count)
{
Check if $count <=10 so the function will not excuted if
$count > 10
if($count <= 10)
{
Print $count followed by a line break
echo $count;
echo "<br />";
Return $count + the result of the same function for $count+1 this which make the function work until reach the if condition $count<=10
return $count + sum($count + 1);
}
}
Note that while you pass 1 as a parameter and the function call itself within it so it will be continues until it reaches 10
$result = sum(1);
echo "The total is $result";
?>

Related

Why PHP prints this function in reverse after swapping two lines without changing the condition

I have a displayNumber code which prints the input number if its greater than 1 and then calls the displayNumber function again with the number - 1.
function displayNumber($number) {
if ($number >= 1) {
echo $number;
displayNumber($number-1);
}
return;
}
displayNumber(10);
The output would be: 10987654321
But after swapping the echo and displayNumber lines:
function displayNumber($number) {
if ($number >= 1) {
displayNumber($number-1);
echo $number;
}
return;
}
displayNumber(10);
The output is now: 12345678910
I can't understand this behavior of PHP.
I modified your code to make it more understandable:
function displayNumber($number) {
if ($number >= 1) {
echo $number ."<br>";
displayNumber($number-1);
echo $number . "---";
}
}
displayNumber(10);
Output:
10
9
8
7
6
5
4
3
2
1
1---2---3---4---5---6---7---8---9---10---
In the first case, values are being printed, then decremented by 1. In the second case, values are decremented by 1 and then printed.
Also, the first echo, runs every time, but this does not happen for the second echo as the function is called just before it.

multiply number by itself PHP [duplicate]

This question already has answers here:
PHP: pass a variable to a function, do something to the variable, return it back
(5 answers)
Closed 3 years ago.
How come the output of these two functions are not the same? Please enlighten me on this one.
first code:
function multiply_itself(&$number) {
$number *= $number;
return $number;
}
$my_num = 10;
echo "$my_num" . "<br>"; //Output 10
multiply_itself($my_num);
echo "$my_num"; //Outputs 100
second code:
function doubled($integer) {
$integer *= $integer;
return $integer;
}
$integer = 20;
doubled($integer);
echo "$integer"; //Outputs 20, why not 400?
The second example outputs 20 because the parameter is not passed by reference like in the first example.
Change the function signature to function doubled(&$integer) or use its return value $integer = doubled($integer); and it prints 400.

How many times the last statement of a recursive function block gets executed?

Consider the below code snippet demonstrating recursion :
<?php
function test() {
static $count = 0;
$count++;
echo $count."<br>";
if($count < 10) {
test();
}
echo "Count Value : ".$count--;
}
test();
?>
Output of above code is as below :
1
2
3
4
5
6
7
8
9
10
Count Value : 10
Count Value : 9
Count Value : 8
Count Value : 7
Count Value : 6
Count Value : 5
Count Value : 4
Count Value : 3
Count Value : 2
Count Value : 1
I expected the last code statement of the function test() i.e. echo "Count Value : ".$count--; will get execute only once when the if condition returns false upon $count = 10; and everything would be finish.
But unexpectedly, I'm getting it executed ten times with decreasing value of variable $count. I'm not understanding how it's happening? How is the code flow getting manipulated here unexpectedly?
As the recursive function call is made inside the if condition how can it get called subsequently for 10 more times even after failing the if condition?
Please explain me.
Note : I haven't forgot to add else and I don't want it. Just explain why and how the last statement is getting executed only after printing nos. from 1 to 10 and only after the failing of if condition. When the if condition was returning true it was not getting executed. How?
I think you forgot the else.
<?php
function test() {
static $count = 0;
$count++;
echo $count."<br>";
if($count < 10) {
test(); // when this call is made, all the code bellow waits for it to return
} else {
echo "Count Value : ".$count--;
}
}
test();
?>
What happens is that every time you call test(), inside the if condition, the execution stops until the newly called test() returns. The test() function only returns when $count >= 10. which means that all hanging functions call will continue. What is a RECURSIVE Function in PHP?
Your code can be translated to something like this;
<?php
function test() {
static $count = 0;
$count++;
echo $count."<br>";
if($count < 10) {
static $count = 1;
$count++;
echo $count."<br>";
if($count < 10) {
static $count = 2;
$count++;
echo $count."<br>";
if($count < 10) {
// ... the code repeats until the point when $count = 9
} else {
echo "Count Value : ".$count--;
}
} else {
echo "Count Value : ".$count--;
}
} else {
echo "Count Value : ".$count--;
}
}
test();
?>
Your code runs 9 times the recursion + 1 from outside, so it should be ok to have 10 total executions.
Here a commented version:
<?php
function test() {
static $count = 0; // initialize only the first run
$count++;
echo $count."<br>"; // Current $count status
if($count < 10) { // goes on until 9
test(); // This function will run before everything else
}
// regardless the value of $count print $count then decreases it
echo "Count Value : ".$count--;
//only the other calls in the stack will see by the -- operator effect
}
test();
?>

is it possible in php loop without nested loop [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I want to print like this using loop without nested loop:
1
2 3
4 5 6 7
8 9 10 11 12 13 14 15
first line start from 1 and print only one integer
second line start from 2 and print two integer
third line start from 4 and print four integer
fourth line start from 8 and print eight integer
(same condition in other line if exist)
A pair of counters should do the trick;
$threshold = 1;
$x = 1;
for($i = 1; $i <= 15; $i++) {
echo $i . ' ';
if($x == $threshold) {
echo "<br>\n";
$threshold = $threshold * 2;
$x = 0;
}
$x++;
}
Will keep on working till infinity, or your script runs out of memory. Whatever comes first :)
You can achieve with single while and some array functions. Try this.
<?php
$start=1;
while($start<=10){
$array = range($start,($start+$start-1));
echo implode(' ',$array)."<br>";
$start=$start*2;
}
?>
something like this?
$i=1;
$t=1;
while($i<1000)
{
if($i==$t)
{
if($t!=1) echo "<br />";
$t=$t*2;
}
echo $i." ";
$i++;
}
same thing but with log($i,2).
<?php
$i=1;
while($i<20)
{
echo $i;
$i++;
if(filter_var(log($i,2), FILTER_VALIDATE_INT))
echo PHP_EOL;
else
echo "\t";
}
You can even do it without any for and some recursion ;-)
<?php
$elements = range(1,15);
display($elements);
function display(array $parts, $step = 1) {
if(! count($parts)) {
return;
}
$elements = array_splice($parts, 0, $step);
echo implode("\t", $elements)."\n";
display($parts, $step * 2);
}
See the working code on https://eval.in/755277

generating a unique no for coupon code 6 to 8 digit for any no of coupon [duplicate]

This question already has answers here:
Generating unique 6 digit code
(6 answers)
Closed 8 years ago.
for($i=0,$ii=1;$i<$_POST['no_of_coupon']; $ii++) {
$unique_code=uniqid();
$category_unique_code = substr($unique_code,rand(0,strlen($unique_code) - 6),6);
$i++;
echo $category_unique_code;
}
$_POST['no_of_coupon'] is the no . For eg. if user want 1 lakh coupon code or more i.e. $_POST['no_of_coupon'], all the code is inserted into the the database and the code is unique but I have tried above method , but its not unique then i tried another method
function gen_random($length=32)
{
$final_rand='';
for($i=0;$i< $length;$i++)
{
$final_rand .= rand(0,9);
}
return $final_rand;
}
for($i=0,$ii=1;$i<$_POST['no_of_coupon']; $ii++) {
$unique_code=gen_random(6);
$category_unique_code = substr($unique_code,rand(0,strlen($unique_code) - 6),6);
$i++;
echo $category_unique_code;
}
This method is also not generating unique coupon code , I just need 6 to 8 digit unique no So somebody have any idea to generate unique no , please tell me
This code will generate an 8 digit unique coupon code:
function getUniqueCouponCode ()
{
$filename = 'number.txt';
if (file_exists($filename)) {
$actual_number = file_get_contents($filename);
} else {
$actual_number = 1;
}
file_put_contents($filename, $actual_number + 1);
return str_pad($actual_number, 8, '0', STR_PAD_LEFT);
}
Try this to create a 6 or 8 digit unique no:
<?php
$date=date('y-m-dh:i:s');
echo substr(md5($date),0,6);
?>

Categories