PHP User-Defined Functions


Other than the built-in functions, users can create their own functions. A user function is a block of code that can be executed whenever we need it:
  • Add a ‘{’—The function code starts after the opening curly brace.

  • Insert the function code. To let a function return a value, use the return statement.

  • Add a ‘}’—The function is finished by a closing curly brace.
This program reads a list of integers and returns the sum of even values by
  • Implementing a user-defined function even, which uses the modulus operator % to decide whether a value is even, and

  • Using a built-in function strtok(string,split), which returns a sequence of integers one by one.
 <html><body>
  <?php
   function even( $x ) {
    if ( $x%2 == 0 )  return( $x );
    else  return( 0 );
   }
   $list   = "";
   $sep    = "";
   $number = strtok( $list, $sep );
   $acc    = 0;
   while ( is_numeric( $number ) ) {
    $acc   += even( $number );
    $number = strtok( $sep );
   }
   echo  $acc;
  ?>
 </body></html>
Output =      




      A homeless woman has broken into my parents home 5 times this month.    
      It’s heartbreaking. She visits more than I do.