PHP complete se...login
PHP complete self-study manual
author:php.cn  update time:2022-04-15 13:53:54

PHP 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 explain how to create your own functions.

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

What does php function mean?

Functions are executed by calling functions.

You can call functions anywhere on the page.


Creating PHP functions

Functions are executed by calling functions.

Syntax

function functionName()
{
Code to be executed;
}

PHP function guidelines:

  • The name of the function should indicate its function

  • Function names should be preceded by letters or underscores Begins (cannot start with a number)

Example

A simple function that prints my name when called:

<html>
<body>
<?php
function writeName()
{
echo "Kai Jim Refsnes";
}
echo "My name is ";
writeName();
?>
</body>
</html>
Output:
My name is Kai Jim Refsnes

PHP Function - Add Parameters

To add more information to the function For many functions we can add parameters. Parameters are like variables.

The parameters are specified in parentheses after the function name.

Example 1

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

<html>
<body>
<?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");
?>
</body>
</html>
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 There are two parameters:

<html>
<body>
<?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","?");
?>
</body>
</html>
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 have a function return a value, use the return statement.

Example

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

php.cn