Jump to content

Could someone tell if this was the best way?


fortnox007

Recommended Posts

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  :wtf:

 

$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);

 

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);

 

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.