Help me to understand this code, please | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Help me to understand this code, please

Hi all, Can someone please explain me how does this code work? ---- <?php function func($num, $ch="sum") { if ($num == 1) return 1; else { if ($ch == "factorial") return $num * func($num - 1, $ch); else return $num + func($num - 1, $ch); } } echo func (5); echo func (5,"factorial"); ?> ---- I am looking at this for 2 days already and I can't get anything. Why we get 15120 as a result??? I can't understand what is happening after the first "else" and till the end... I know how factorial should be calculated, but this is some another thing. I would appreciate any detailed explanation of these strings... Thank you!

24th Jul 2017, 8:50 AM
Danil Dots
Danil Dots - avatar
4 Answers
+ 11
This is a question I submitted (I didn't think it would be approved but it was approved). Here's the solution. The function takes a number and a string as input. 1) If input string is "factorial", the factorial of the input number is returned. 2) If input string is "sum", the sum of numbers till the input number is returned. func(5) => input number is 5 and input string is "sum" (default). So, sum of numbers till 5 = 1+2+3+4+5 = 15 is returned. func(5, "factorial") => input number is 5 and input string is "factorial". So, factorial of 5 = 5! = 120 is returned.
24th Jul 2017, 9:08 AM
Krishna Teja Yeluripati
Krishna Teja Yeluripati - avatar
+ 4
I recognised that question! Wait i think we have to remive linebreaks to get that
24th Jul 2017, 9:10 AM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
0
@S Vengat, just copy everything between ---- and ---- and it will work :)
24th Jul 2017, 9:29 AM
Danil Dots
Danil Dots - avatar
0
Thank you, @Krishna, you are my Jesus Christ.
24th Jul 2017, 9:42 AM
Danil Dots
Danil Dots - avatar