PHP Functions

PHP Functions

The real power of PHP comes from its functions.

PHP has more than 1000 built-in functions, and in addition, you can create your own custom functions to make your code modular and reusable.


Creating a Custom Function

A user-defined function declaration starts with the word function.

Function Example

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

writeMsg(); // Call the function ?>

Function Arguments & Returning Values

Information can be passed to functions through arguments. An argument is just like a variable. If you want a function to return a computed value back to you instead of printing it directly, use the return statement.

Return Example

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

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