+ 2

How this function working and what's mean by $u = $u + $y? And explain more about return (i mean what next after "return $u?" )

<?php function a($w) { $u=0; { for ($y=0;$y<$w;$y++) $u = $u + $y; } return $u; } echo a(7); ?>

19th Oct 2017, 5:11 AM
Irezer
Irezer - avatar
4 Antworten
+ 1
Hi Designing. Thanks for the reply. And want to know what does it means by "return the value" as you mention. Return to where? o.o And also the output "echo a(7);" is 21. why o.o
19th Oct 2017, 8:11 PM
Irezer
Irezer - avatar
+ 1
Let try to explain 1)The $ sign in PHP is a mandatory first sign in variable name, So $u = $u + $y means like u=u+y in another program languages, adding value of variable y into u. 2) w is here a passed parameter into function (see last line), ts 7. 3) The -for- is a command to repeat the next command ($u = $u + $y;) under given condition 4) The condition here is $y=0;$y<$w,,so from 0 to less number than 7. 5) So, in this cycle for are added sequentialy into w numbers 0,1,2,3,4,5,6, 6) At the ending, as the result , the number in w is 21. 7) Ccommand return - simply returns a value into a line, from there the function was called and here is used like a counted result of this function. 8) So the command echo writes to output the returned value 21.. (In fact. writes to output, only if you use PHP as some alone compiler , like here in course. When using it like a backend in website, the echo generates this number into own web page, which is sent over internet to the client. But this is another story.
19th Oct 2017, 8:23 PM
Petr Hatina
Petr Hatina - avatar
+ 1
>>"return a value into a line", which line (*-*). Is it after "return $u;" will go to line "$u=0;" or "function a($w)" or other lines? I had written the last line, that means the echo a(7); line. Of course it not depends on fact if the line is the last , or first after the return command/ But the important is to use name of the function with parenthesis (and sending value as parametr) without a -function- word before. Like echo a(7); or $anothervariable= a(100). when the a is name of the functiom This is the caliing of this functiom and here is returned the value from return command
19th Oct 2017, 9:12 PM
Petr Hatina
Petr Hatina - avatar
0
Hi Petr Hatina. Thanks for the explaination. But for no.7 of your elaboration, i still don't get it, sry. "return a value into a line", which line (*-*). Is it after "return $u;" will go to line "$u=0;" or "function a($w)" or other lines?
19th Oct 2017, 8:39 PM
Irezer
Irezer - avatar