
A function is a self-contained piece of code which carries out a particular task or function. benefit of using functions is that they are reusable
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | <?php //Defining a Function //syntax for defining a function function addNumbers( $num1 , $num2 ) { $result = $num1 + $num2 ; return $result ; } $total = addNumbers(5, 10); //echo $total; //result 15 //Organizing Functions function hello() { echo "<h1>HELLO!</h1>" ; echo "<p>Welcome to my web site</p>" ; } function printBreak( $text ) { echo "$text<br>" ; } function addNumbers( $num1 , $num2 ) { return $num1 + $num2 ; } echo hello(); echo printBreak( "This is a line" ); echo addNumbers(3.75, 5.645); //9.39536.75 //Accepting a Variable Number of Arguments function calcAverage() { // initialize value to be used in calculation $total = 0; // find out how many arguments were given $arguments = func_num_args(); // loop to process each argument separately for ( $i = 0; $i < $arguments ; $i ++) { // add the value in the current argument to the total $total += func_get_arg( $i ); } // after adding all arguments, calculate the average $average = $total / $arguments ; // return the average return $average ; } // invoke the function with 5 arguments //echo calcAverage(44, 55, 66, 77, 88); //output 66 // invoke the function with 8 arguments echo calcAverage(12, 34, 56, 78, 90, 9, 8, 7); //ouput 36.75 |