If there is a task in your program that you need to execute repeatedly, you can create a function instead of writing code at different places in the program for that task, and whenever you need to perform that task You can call that function at different places.
Functions are the basic structure of any program. Like C, PHP is also a modular language. You use function keywords to create a function in PHP. The most unique thing about PHP functions is that you can create another function in a function and create a class as well.
User-defined Functions
Those functions that are created by the programmer are called user defined functions. To create a function in PHP, you have to use function keyword. The basic function structure of PHP is being given below.
<?php function func_Name(arg1, arg2) { // Perform any task here } ?>
You can call the given function as follows.
<?php // Defining function function myAddFunction($a, $b) { return $a + $b; } // Calling function with arguments $result = myAddFunction(3,5); echo "<h2>Addition is $result</h2>"; ?>
When you create a function in PHP, you can also give a default argument. When the user passes no argument during the function call, the default argument is used.
To give a default argument to any function, you write the default argument of assigning assignment operator (=) in front of it. Its example is being given below.
<?php // Defining default argument function course($subject = "hindi") { echo "<h2>Welcome $subject</h2>"; } course(); ?>