Functions - nogsantos/study-zce-php-certification-codes GitHub Wiki

Basic

  • PHP function names are not case-sensitive.
  • All functions in PHP return a value—even if you don’t explicitly cause them to. Thus, the concept of “void” functions does not really apply to PHP.
  • Naturally, return also allows you to interrupt the execution of a function and exit it even if you don’t want to return a value:
<?php
function hello($who){
   echo "Hello $who";
   if ($who == "World") {
      return; // Nothing else in the function will be processed
   }
   echo ", how are you";
}
hello("World"); // Displays "Hello World"
hello("Reader") // Displays "Hello Reader, how are you?" 
?>

Note, however, that even if you don’t return a value, PHP will still cause your function to return NULL.

PHP provides three built-in functions to handle variable-length argument lists:

  • func_num_args()
    Returns the number of arguments passed to the function
<?php
function foo(){
    $numargs = func_num_args();
    echo "Number of arguments: $numargs\n";
}
foo(1, 2, 3);
?>
  • func_get_arg()
    Gets the specified argument from a user-defined function's argument list.
<?php
function foo(){
     $numargs = func_num_args();
     echo "Number of arguments: $numargs<br />\n";
     if ($numargs >= 2) {
         echo "Second argument is: " . func_get_arg(1) . "<br />\n";
     }
}
foo (1, 2, 3);
?>
  • func_get_args()
    Gets an array of the function's argument list.
<?php
function foo(){
    $numargs = func_num_args();
    echo "Number of arguments: $numargs<br />\n";
    if ($numargs >= 2) {
        echo "Second argument is: " . func_get_arg(1) . "<br />\n";
    }
    $arg_list = func_get_args();
    for ($i = 0; $i < $numargs; $i++) {
        echo "Argument $i is: " . $arg_list[$i] . "<br />\n";
    }
}
foo(1, 2, 3);
?>
⚠️ **GitHub.com Fallback** ⚠️