WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

PHP 5 Functions



The true power of PHP comes from its functions.

In PHP, more than 1000 built-in functions are provided.


PHP built-in functions

For a complete reference manual and examples of all array functions, please visit our PHP Reference Manual .


PHP functions

In this chapter, we will show you how to create your own functions.

To execute the script when the page loads, you can put it in a function.

The function is executed by calling the function.

You can call functions anywhere on the page.


Syntax

The function is executed by calling the function.

<?php function functionName() { // Code to execute } ?>

PHP function guidelines:

  • The name of the function should suggest its function
  • The function name starts with a letter or underscore (cannot start with a number)

Example

A simple function that outputs my name when called:

Example

<?php function writeName() { echo "Kai Jim Refsnes"; } echo "My name is "; writeName(); ?>

Output:

My name is Kai Jim Refsnes


PHP functions-add parameters

In order to add more functions to the function, we can add parameters, which are similar to variables.

The

parameter is specified in parentheses after the function name.

Instance 1

The following example will output different first names, but the last names are the same:

Example

<?php function writeName($fname) { echo $fname . " Refsnes.<br>"; } echo "My name is "; writeName("Kai Jim"); echo "My sister's name is "; writeName("Hege"); echo "My brother's name is "; writeName("Stale"); ?>

Output:

My name is Kai Jim Refsnes.
My sister's name is Hege Refsnes.
My brother's name is Stale Refsnes.

Example 2

The following function has two parameters:

Examples

<?php function writeName($fname,$punctuation) { echo $fname . " Refsnes" . $punctuation . "<br>"; } echo "My name is "; writeName("Kai Jim","."); echo "My sister's name is "; writeName("Hege","!"); echo "My brother's name is "; writeName("Ståle","?"); ?>

Output:

My name is Kai Jim Refsnes.
My sister's name is Hege Refsnes!
My brother's name is Ståle Refsnes?

PHP function-return value

To make a function return a value, use a return statement.

Example

<?php function add($x,$y) { $total=$x+$y; return $total; } echo "1 + 16 = " . add(1,16); ?>

Output:

1 + 16 = 17