fortnox007 Posted September 9, 2010 Share Posted September 9, 2010 Hi all I just learned a bit on how to write functions since I want to get things more organized and I made the following after I read about foreach loops and functions. If anyone has tips hints or please tell me i am one eager monkey $employeeAges["Lisa"] = "28"; $employeeAges["Jack"] = "16"; $employeeAges["Ryan"] = "35"; $employeeAges["Rachel"] = "46"; $employeeAges["Grace"] = "34"; function bla($array){ foreach($array as $key => $value){ echo "name: {$key} age: {$value}.<br />\n"; } } echo bla($employeeAges); I made another function that sums up the ages (at least that's what i want but it's not working good lols any helps is apreciated function sum_ages($array){ foreach($array as $key => $value){ $total += $value; return $total; } } echo sum_ages($employeeAges); Quote Link to comment Share on other sites More sharing options...
schilly Posted September 9, 2010 Share Posted September 9, 2010 your return is inside the loop so it returns right away. function sum_ages($array){ foreach($array as $key => $value){ $total += $value; } return $total; } Quote Link to comment Share on other sites More sharing options...
fortnox007 Posted September 9, 2010 Author Share Posted September 9, 2010 Ah thats why it outputed 28 (the first in the array) hehe awesome. Ty for your swift respond! hehe I now also learned where to position the return(), before this i had really no idea : ) ty Quote Link to comment Share on other sites More sharing options...
fortnox007 Posted September 9, 2010 Author Share Posted September 9, 2010 small question though, about the return, Incase i would have had a function with an if {} else{} would I have used 2 returns than? seems logical to me : ) -edit: hmm I just tried that with the folowing but i dont see where to put a second return lol function works though: $lalala = 5; function moo($num){ if ($num > 10){ $message = "mooOOoOOO 10+"; }else{ $message = "mooOOoooO 10-"; }return $message; } echo moo($lalala); Quote Link to comment Share on other sites More sharing options...
schilly Posted September 9, 2010 Share Posted September 9, 2010 You only need one for that as the code will always get to that return. If you start writing bigger functions with more code that you want to exit on a certain cases without executing a bunch of code afterwards then you would use multiple returns. Quote Link to comment Share on other sites More sharing options...
fortnox007 Posted September 9, 2010 Author Share Posted September 9, 2010 OK cool thanks a lot, : ) i am now going to try and make the function with the ternary operator (still need to understand that). But i consider this mystery solved. Thank you!! Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.