Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

PhP function


May 11, 2021 PHP


Table of contents


PhP function


The true power of PHP comes from its functions.

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

Any valid PHP code can appear inside functions, even other functions and class definitions.


PHP built-in functions

To view the full reference manual and examples of all array functions, please visit our PHP Reference Manual.


PhP function

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

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

Functions are executed by calling functions.

You can call functions anywhere on the page.


Create a PHP function

Functions are executed by calling functions.

Grammar

function functionName ()
{
Code to be executed ;
}

PHP function guidelines:

  • The name of the function should indicate its functionality

  • The function name begins with a letter or underscore (cannot begin with a number)

Instance

A simple function that outputs my name when it is 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 functionality to the function, we can add parameters. Arguments are similar to variables.

The argument is specified in parentheses after the function name.

Instance 1

The following example will output a different name, but the last name is the same:

<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.

Instance 2

The following function has two arguments:

<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?

The PHP function passes information to the function through the argument list, which is a list of expressions with commas as separators. PhP parameters are valued from left to right.


PHP function - Returns a value

To get the function to return a value, use the return statement.

Instance

<html>
<body>

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

echo "1 + 16 = " . add(1,16);
?>

</body>
</html>

Output:

1 + 16 = 17