A function is a piece of code in a larger program. The function performs a specific task. The advantages of using functions are:
PHP function because there are already more than 1000 of built-in library functions created for different area and you just need to call them according to your requirement.
You already have seen many functions in previous tutorials like file system fopen(), fclose(), fread() and fwrite() etc. They are built-in functions but PHP gives you option to create your own functions as well.
Its very easy to create your own PHP function. Suppose you want to create a PHP function simply set a message which will be show on your browser when you will call it. This example creates a simple php function called myFirstFunction() and then calls it just after creating it.
Note : While you creating a function its name should be start with keyword function and all the PHP code should be put inside { and } braces as shown in the following example below −
<?php /* Defining a PHP Function */ function myFirstFunction() { echo "Hello I am phpkida, How r U!"; } /* Calling a PHP Function */ myFirstFunction(); ?>
PHP gives you option to pass your parameters inside a function. You can pass one or more then one parameters you like. These parameters work like variables inside your function.
This example takes two integer parameters and add them together and then print them.
<?php function addFunction($num1, $num2) { $sum = $num1 + $num2; echo "Sum of the two numbers is : $sum"; } addFunction(10, 20); ?>
PHP gives you option to pass arguments to functions by reference. This means that a reference to the variable is manipulated by the function rather than a copy of the variable’s value.
If you want made any changes to an argument in these cases you will change the value of the original variable. You can pass an argument by reference by adding an ampersand to the variable name in either the function call or the function definition.
<?php function addNum($num) { $num += 5; } function addNum1(&$num) { $num += 6; } $ab = 10; addNum( $ab); echo "Original Value is $ab<br />"; addNum1( $orignum ); echo "Original Value is $ab<br />"; ?>
A function can return a value using the return statement in conjunction with a value or object. return stops the execution of the function and sends the value back to the calling code.
Example
<?php function addNum($num1, $num2) { $sum = $num1 + $num2; return $sum; } $return_value = addNum10, 20); echo "Returned value from the function : $return_value"; ?>