PHP has a huge collection of internal or built-in functions that you can call directly within your PHP scripts to perform a specific task, and in addition you can create your own custom functions.
Built-in Functions
PHP has over 1000 built-in functions that can be called directly, from within a script, to perform a specific task.
User-Defined Functions
It is possible to create your own function. A function has the following characteristics:
- can be used repeatedly in a program.
- will not be executed automatically when a page loads
- can be executed by a function call
Creating a User-Defined Function
Creating a function in PHP uses the following syntax:
function functionName() {
code to be executed;
}
Take note that a function in PHP:
- starts with the word
function
- function names are NOT case-sensitive
- it is a common practice to name a function with what it actually does
Below is a simple example of a PHP function.
<?php
function helloWorld() {
echo "Hello world! <br>";
}
helloWorld(); // call the function
Functions with Parameters
When defining a function, parameters can be included so that it will take input values at run time. The parameters act similarly to placeholder variables within a function; they are replaced at run time by the values (known as arguments) sent to the function at the time of invocation.
Below is an example of a function with parameters.
<?php
// Defining function
function getSum($x, $y){
$sum = $x + $y;
echo "Sum of the two numbers $x and $y is : $sum";
}
// Calling the function
getSum(11, 21);
Note that functions with parameters can only be called together with the exact number of parameters. For functions that accepts parameters as an option, a default value should be assigned to its parameters. Below is an example of a function that has optional parameters.
<?php
// Defining function
function getSum($x , $y = 10){
$sum = $x + $y;
echo "Sum of the two numbers $x and $y is : $sum";
}
// Calling function
getSum(11, 21);
echo "<br>";
getSum(3, 43);
echo "<br>";
getSum(5); //function is called using only one parameter
echo "<br>";
Exercise
Create a function named myFunction
. This function accepts two integers($x
, $y
) as parameters. It then takes the first integer and divides it with the second integer and displays the quotient. To test your code, call your function with 12 as your first integer and 3 as the second.
<?php
$var = 123;
<?php
function myFunction($x, $y){
$z = $x / $y;
echo "$x divided by $y is $z";
}
myFunction(12, 3);
{
"test_variable_exists":[
{
"object":"$x",
"error_message":"Have you declared <code>$x<\/code>?"
},
{
"object":"$y",
"error_message":"Have you declared <code>$y<\/code>?"
}
],
"test_output_contains":
{
"expected":"4",
"error_message":"Sorry. Please try again."
},
"test_function_exists":
{
"object":"myFunction",
"error_message":"Did you create <code>myFunction<\/code>?"
},
"success_message":"Good job!",
"error_message":"Please read the instructions again."
}