+ 1

Why this code when return @abc just output a but if i echo $abc then call solo() the code runs correctly??

https://code.sololearn.com/wd17sBEKnTYx/?ref=app

14th Jul 2017, 5:59 AM
mahdi
mahdi - avatar
7 Réponses
+ 3
Once you return in the for loop the for loop is exited and no further iterations of the loop occur. You could do something like this: <?php $abc = "abcdef"; function solo() { global $abc; for($k=0;$k<3;$k++) { print $abc[$k]; } } echo solo(); ?> Or this: <?php $abc = "abcdef"; function solo() { global $abc; $str = ""; for($k=0;$k<3;$k++) { $str .= $abc[$k]; } return $str; } echo solo(); ?>
14th Jul 2017, 7:02 AM
ChaoticDawg
ChaoticDawg - avatar
+ 9
when a function reaches a return statement it exits, so in your case it enters the loop and exits returning the first char in the string, which is "a".
14th Jul 2017, 6:56 AM
Nikolay Nachev
Nikolay Nachev - avatar
+ 5
Return is like a one-way line. It kinda is the break keyword of loops. To make it better replace return with echo. And remove that echo when you call it.
14th Jul 2017, 8:16 AM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
+ 2
You could using the second version in my post. Just save the returned string in the file.
14th Jul 2017, 9:38 AM
ChaoticDawg
ChaoticDawg - avatar
+ 2
Then you modify the code to add the <br> either in the function or where you're saving to the file or however else you see fit that does what you're looking for.
14th Jul 2017, 9:46 AM
ChaoticDawg
ChaoticDawg - avatar
0
but i wanna save the result in txt file with ur code i couldnt do that @chaoticdawg
14th Jul 2017, 9:32 AM
mahdi
mahdi - avatar
0
and if i want put <br> between them?
14th Jul 2017, 9:41 AM
mahdi
mahdi - avatar