HOME HTML EDITOR C JAVA PHP

PHP Functions

The real power of PHP comes from its functions. PHP has more than 1000 built-in functions, and besides those, you can create your own custom functions to perform specific tasks.

1. Create a User Defined Function

A user-defined function declaration starts with the word function. A function name must start with a letter or an underscore.

<?php
  function writeMsg() {
    echo "Hello world!";
  }

  writeMsg(); // call the function
?>

2. Function Arguments

Information can be passed to functions through arguments. An argument is just like a variable. You can add as many arguments as you want, just separate them with a comma.

<?php
  function familyName($fname) {
    echo "$fname Experts.<br>";
  }

  familyName("Java");
  familyName("Python");
  familyName("PHP");
?>

3. Default Argument Value

If we call the function without an argument, it takes the default value as provided in the function definition.

<?php
  function setHeight($minheight = 50) {
    echo "The height is : $minheight <br>";
  }

  setHeight(350);
  setHeight(); // will use the default value of 50
?>

4. Returning Values

To let a function return a value, use the return statement. This is useful when you want the function to calculate something and give the result back to the script.

<?php
  function sum($x, $y) {
    $z = $x + $y;
    return $z;
  }

  echo "5 + 10 = " . sum(5, 10);
?>

5. Type Declaration

In PHP 7 and later, you can specify the expected data type for arguments and the return value.

<?php
  function addNumbers(int $a, int $b): int {
    return $a + $b;
  }
  echo addNumbers(5, 5);
?>
Tip: Always give your functions a name that reflects what the function does! This makes your code much easier to read and maintain for yourself and others.