PHP - Function Function declaration

Introduction

A function has a name, arguments, and a block of code.

Optionally, it can return some value.

The name of the function has to follow the same rules as variable names.

It has to start with a letter or an underscore, and can contain any letters, numbers, or underscore.

The function's name cannot be a reserved word.

Demo

<?php
     function addNumbers($a, $b) { 
        $sum = $a + $b; /*from  w  w  w  . jav a2  s. co m*/
        return $sum; 
     } 
     $result = addNumbers(2, 3); 
?>

Here, the function addNumbers takes two arguments: $a and $b.

The block of code defines a new variable $sum, which is the sum of both arguments, and then returns its content.

To use this function, call it by its name while sending all the required arguments.

Related Topics