PHP Functions

PHP Functions can be seen as ‘block of code’ or ‘set of statements’ that perform some tasks when executed. A function usually takes some input arguments, perform some action on them and returns some result.

Example of a Simple PHP Function:

<?php
function greetings()
{
	echo "Hello";
}
         
greetings();
?>
Tutorials Class - Output Window

Hello


PHP Function With Arguments

You can pass some input arguments (also called parameters) into the functions. An argument is just like a variable on which you can perform some action.

<?php
function add($num1, $num2)
{
    $total = $num1 + $num2;
    echo "Sum of the two numbers is : $total";
}
add(10, 25);
?>
Tutorials Class - Output Window

Sum of the two numbers is : 35

Above function with take two arguments 10 & 25. Then, it perform addition operation on those numbers and returns total sum.


Function With Default Parameters Value

You can set a function with default parameter. When you can that function without passing that parameter, default parameter will be passed.

<?php
function setAge($age = 25) 
{
    echo "My age is: $age";
}
 
setAge(50);
echo "<br>";
setAge(); // This time function will use the default value of 25
echo "<br>";
setAge(35);
?>
Tutorials Class - Output Window

My age is: 50
My age is: 25
My age is: 35


Function Returning Values

A function can return a value using the return statement. After ‘return’ the execution of the function stops and sends the return value back to the calling code.

<?php
function add($x, $y) 
{
    $z = $x + $y;
    return $z;
}
 
echo "The sum of 5 + 10 is: " . add(5, 10);
?>
Tutorials Class - Output Window

The sum of 5 + 10 is: 15


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
Factorial program in PHP using recursive function
Write a PHP program to check if a person is eligible to vote
Write a PHP program to calculate area of rectangle
Interview Questions & Answers
What is PHP Function?
What is PHP floor() function?