PHP Functions

In PHP, there are more than 700 built-in functions. You should  know where and how can use these functions.

Create a PHP Function

A function will be executed by a call to the function.

Syntax

function functionName()
{
code to be executed;
}

  • Give the function a name that reflects what the function does
  • The function name can start with a letter or underscore (not a number)
Example:
<html>
<body>
<?php
function writeName()
{
echo "Neilsen Samtek";
}
echo "My name is ";
writeName();
?>
</body>
</html>

Click to see output

PHP Functions - Adding parameters

To add more functionality to a function, we can add parameters. A parameter is just like a variable.
Parameters are specified after the function name, inside the parentheses.

Example:

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

Click to see output

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

Click to see output

PHP Functions - Return values

To let a function return a value, use the return statement.
<html>
<body>
<?php
function add($x,$y)
{
$total=$x+$y;
return $total;
}
echo "1 + 16 = " . add(1,16);
?>

</body>
</html>

Click to see output