Let me understand this recursive function of PHP [closed] - php

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 7 years ago.
Improve this question
I am trying to understand this recursive function. When i echo out with different numbers it returns different result. I can't understand how this is working actually.
<?php
function head_sum($x) {
return ($x == 1) ? $x : $x + head_sum($x - 1);
}
echo head_sum(5);//15
echo head_sum(2);//3
echo head_sum(3);//6

Your function right now says:
if variable x equals 1 then
return variable x
else
return variable x + this function( variable x -1 )
So this will keep running until $x equals 1. Until then it will keep adding itself.
So when you type echo head_sum(5):
head_sum(5); //$x = 5
head_sum(4); //$x = 5+4
head_sum(3); //$x = 5+4+3
head_sum(2); //$x = 5+4+3+2
head_sum(1); //$x = 5+4+3+2+1 = 15
This can also be represented like this (hope i can show this properly without whiteboard)
function headsum(5){
return 5 + head_sum( 5-1 ){
return 4 + head_sum( 4-1 ){
return 3 + head_sum( 3-1 ){
return 2 + head_sum( 2-1 ){
return 1
}
}
}
}
}
Hope This makes some sense :)

Every time you call head_sum it's called multiple times.
First pass-through goes all the way until the inner head_sum calls itself.
It continues to do so until it decreased by 1 down to 1 at which point the conditional exits out.
So for head_sum(5)
5 goes in and i saved to $x.
Inside recursion calls
head_sum( 5 -1 ) // 4
Then 3
Then 2
Then 1
The ( $x == 1 ) check exits the function after adding the total tally which at this point is incremented to:
5 + 4 + 3 + 2 + 1 = 15

Related

PHP FPDF add new page when Y reach a certain point in foreach

i have the following codes in FPDF :
foreach($dataas $data){
$this->setFont('Arial','', 7);
$this->SetY(105);
$y = $this->GetY();
$valY += 10;
$b = $y + $valY;
$pageH = $this->getPageHeight();
if($b > 200){
$this->AddPage();
$b = 10;
}
$this->SetXY(5,$b);
$this->MultiCell($w[0],3,$sum++,0,'L');
$this->SetXY(17,$b);
$this->MultiCell($w[1],3,$data['data1'],0,'L');
$this->SetXY(50,$b);
$this->MultiCell($w[2],3,$data['data2'],0,'C');
$this->SetXY(65,$b);
$this->MultiCell($w[3],3,$data['data3'],0,'C');
$this->SetXY(82,$b);
$this->MultiCell($w[4],3,$data['data4'],0,'C');
$this->SetXY(97,$b);
$this->MultiCell($w[5],3,$data['data5'],0,'C');
$this->SetXY(114,$b);
$this->MultiCell($w[6],3,$data['data6'],0,'L');
$this->SetXY(125,$b);
$this->MultiCell($w[7],3,number_format($data['data7'],2,".",","),0,'L');
$this->SetXY(143,$b);
$this->MultiCell($w[8],3,number_format($data['data8'],2,".",","),0,'L');
$this->SetXY(161,$b);
$this->MultiCell($w[9],3,number_format($data['data9'],2,".",","),0,'L');
$this->SetXY(186,$b);
$this->MultiCell($w[10],3,number_format($data['data10'],2,".",","),0,'L');
$this->SetXY(204,$b);
$this->MultiCell($w[11],3,number_format($data['data11'],2,".",","),0,'L');
$this->SetXY(222,$b);
$this->MultiCell($w[12],3,number_format($data['data12'],2,".",","),0,'L');
$this->SetXY(247,$b);
$this->MultiCell($w[13],3,number_format($$data['data13'],2,".",","),0,'L');
$this->SetXY(272,$b);
$this->MultiCell($w[14],3,$data['data14'],0,'L');
$this->SetAutoPageBreak(false);
}
this is what i get :
page 1
1
2
3
4
5
page 2
6
page 3
7
page 4
8
but instead i want something like this:
page 1:
1
2
3
4
5
page 2:
6
7
8
9
10
everytime the value of Y hit 200, it adds a new page and also reset the Y on the new page back to 10 but the Y value outside IF didnt change to 10 and i need the foreach to loop the data.
how do i make Y outside IF set to 10 like the above?
thanks in advance!

Find similar value in array, return the key [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 4 years ago.
Improve this question
I got an example array as such
$array = (685,748,810,904,998); // etc
/index 0 1 2 3 4
Let's say I want to find a number 790. As a return, I want to get the index number, in this case, it will be 1 ( because 790 is greater than 1 and lower than 2 ). I would like the final result also to have a measurement, how much % 790 is missing towards 810 ( index + 1 )
I am using PHP 7+
<?php
$input = 820;
$array = array(685,748,810,904,998);
for($i=0;$i<count($array);$i++){
if($input>$array[$i]){
continue;
}
else{
$result = $array[$i] - $input;
echo "require ".$result. ' for next level';
break;
}
}
Above code will search for the value that is higher than your input in your array and give you the diff result for the next step. Then exit the loop with a break.
Output will be like this:
require 84 for next level

Trying to get the most of the random element possibily from first 4 items in array php [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Hi am having 10 elements in array . Am trying to get my random element mostly from first 5 elements. Which means random element appearance from first 5 elements should be much greater than next 5 elements
$arr = array('a','b','c','d','e','f','g','h','i','j');
$random = $arr[array_rand($arr)];
Am using above one to get the random element normally
Use function rand(min_num, max_num):
function rand5($array) {
$part = rand(1, 10);
return ($part > 3) ? $array[rand(0, 4)] : $array[rand(5, 9)];
}
$arr = array('a','b','c','d','e','f','g','h','i','j');
$random = rand5($arr);
Try this simple and easy code :-
$arr = array('a','b','c','d','e','f','g','h','i','j');
$rand = rand(0,9);
echo $arr[($rand <= 6 ? ($rand%5) : $rand)];
You just have to get the random number between 0 to 9 and divide that number in 70%(0-6) and 30%(7-9). If its greater than 5 then only use the remainder else directly get that number
Here is the fiddle :- https://3v4l.org/TWGJJ

How to get the numbers after the decimal place for an if statement in php [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 7 years ago.
Improve this question
I am just trying to figure out how I can get the actual digits of a figure that has been calculated within php and formatted to have 2 decimal places.
so say its calculated it to be 45.76 I am trying to figure out how I can get the 76 from it for an if statement. Basically I want it to look and just say that if it's 00 then remove them, if not, show them.
Thanks
Try :
function showDecimals($v){
$n = abs($v);
$whole = floor($n);
$fraction = $n - $whole;
return $fraction > 0
}
And...
if (showDecimals(10.15)){
//Show
}else{
//Remove?
}
You want to show a whole number if there is no decimal place, and 2 decimals of precision if not?
Method 1
function formatNumber($n) {
$n = round($n*100)/100;
return ''+$n;
}
This simply rounds it to 2 decimals of precision. Zero truncation is automatic.
Usage
echo formatNumber(0); //0
echo formatNumber(0.5); //0.5
echo formatNumber(0.894); //0.89
echo formatNumber(0.896); //0.9
echo formatNumber(1.896); //1.9
Method 2
Or if you 1.9 to display as 1.90, I suppose this would work:
function formatNumber($n) {
if ($n == 0)
return ''+$n;
$str = ''.round($n*100)/100;
$dotpos = strrpos('.', $str);
if (strlen(substr($str, $dotpos+1)) === 2)
$str .= '0';
return $str;
}
Usage:
echo formatNumber(0); //0
echo formatNumber(0.5); //0.50
echo formatNumber(0.894); //0.89
echo formatNumber(0.896); //0.90
echo formatNumber(1.896); //1.90
Edit: Accidentally posted broken version of method 2, should be fixed now.

PHP loop (for each day of a week and each hour) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I want to create a loop (the result will be inserted into javascript)
Syntax:
The first number is the day (Monday - Friday/1 - 5)
The second number is the hour (1 - 11)
So this is finally what the loop should return:
subject_1_1: $("#subject_1_1").val(),
subject_2_1: $("#subject_2_1").val(),
subject_3_1: $("#subject_3_1").val(),
subject_4_1: $("#subject_4_1").val(),
subject_5_1: $("#subject_5_1").val(),
subject_1_2: $("#subject_1_2").val(),
subject_2_2: $("#subject_2_2").val(),
subject_3_2: $("#subject_3_2").val(),
subject_4_2: $("#subject_4_2").val(),
subject_5_2: $("#subject_5_2").val(),
subject_1_3: $("#subject_1_3").val(),
until
subject_5_11: $("#subject_5_11").val()
The last element shouldn't have a comma.
// first sets x = 1, then, while x isn't equal to 5 the code
// inside `{ ... }` is executed and x is added 1
for($x=1;$x<=5;$x++){
// again, but this time with y, from 1 to 11.
for($y=1;$y<=11;$y++){
// So we end up here and we now this code is going to execute
// elevent times for each x value, and a total of 5 x values.
// thats (x = from 1 to 5) * (y = from 1 to 11).
// This string is printed (`echo`) every time for each iteration.
echo "subject_1_3: $(\"#subject_".$x."_".$y."\").val()".(!($x==5&&$y==11)?",":"")."\n";
}
}
Edited 1: now removes last comma.
Edited 2: added comments, but read:
In the string being printed, I notice this code:
!($x==5&&$y==11)?",":""
That does the following:
if this is true ? this is executed : and if it is not, then this is executed
So, in pseudo:
(if not (x=5 and y = 11)) then (print comma) else (don't)
Why not do it in the JavaScript itself?
var obj, x, y;
obj = {}; // this will be the object your subject_X_Y properties belong to
for( x=1; x<=5; x++) {
for( y=1; y<=11; y++) {
obj['subject_'+x+'_'+y] = $('#subject_'+x+'_'+y).val();
}
}

Categories