πŸ“š PHP Tutorial

PHP Tutorial

Learn PHP concepts with simple explanations, examples and practical notes.

Functions in PHP

A function is a piece of code or self contained block of code that is used to perform a particular task.

The main advantage of functions is that code reusability (Write once Invoke multiple).

PHP supports both built-in and user-defined functions. And PHP supports thousands of built-in functions and allows us to define own functions, by using "function" keyword.


Syntax:

function fun_name ()
{
	//code
}

 Note : Function name must be starts with a letter or underscore only.

Simple Function

A simple function is a function without any arguments or parameters.

Example: "FunSimple.php"


Output :

image

Parameterized Functions

A Parameterized functions are functions with parameters.i.e. These functions allow us to pass one or more parameters inside the function.

We can pass the information in function through arguments (or) parameters which are separated by comma (,).

These passed arguments (or) parameters acts as variables inside the function.

Example: "FunParam.php"


Output :

image

Function Call by Value & Reference

PHP allow us to call the function by value and reference.

☞ Call by Value:

In case of call by value, the actual value is not modified even if it is modified inside the function.

Example: "FunCallByValue.php"

Output :

image

☞ Call by Reference:

In case of call by reference, the actual value is modified if it is modified inside the function.

In this case, we need to use & (ampersand) symbol with formal arguments or parameters. And & (ampersand) symbol represents reference of a variable.

Example: "FunCallByReference.php"

Output :

image

Default argument function

PHP allow us to define default argument values in the function. In this case if we don’t pass any value to the function, it will use default argument value.

Example1: "FunDefaultParam.php"

Output :

image

Example2: "FunDefaultParamd.php"

Output :

image

Recursive function

PHP allow us to use recursive function. In this case, we call the current function within the same function. It is also known as recursion.

Example: "FunRecursive.php"

Output :

image