Free download web templates, books and more. Free php projects ,games and apps. GTA mods and more

Breaking

PHP Function || How To Use PHP Function

PHP Functions

the php function very important method for all php pages.
PHP function is a piece of code that can be reused many times. It can take input as argument list and return value. There are thousands of built-in functions in PHP.
In PHP, we can define Conditional functionFunction within Function and Recursive function also.

PHP User-defined Functions

We can declare and call user-defined functions easily. Let's see the syntax to declare user-defined functions.

Syntax

  1. function functionname(){  
  2. //code to be executed  
  3. }  

PHP Functions Example

File: function1.php
  1. <?php  
  2. function sayHello(){  
  3. echo "Hello PHP Function";  
  4. }  
  5. sayHello();//calling function  
  6. ?>  
Output:
Hello PHP Function

PHP Function Arguments

We can pass the information in PHP function through arguments which is separated by comma.
PHP supports Call by Value (default), Call by ReferenceDefault argument values and Variable-length argument list.
Let's see the example to pass single argument in PHP function.
File: functionarg.php
  1. <?php  
  2. function sayHello($name){  
  3. echo "Hello $name<br/>";  
  4. }  
  5. sayHello("sam");  
  6. sayHello("mani");  
  7. sayHello("Johny");  
  8. ?>  
Output:
Hello Sam
Hello many
Hello Johny
Let's see the example to pass two argument in PHP function.
File: functionarg2.php
  1. <?php  
  2. function sayHello($name,$age){  
  3. echo "Hello $name, you are $age years old<br/>";  
  4. }  
  5. sayHello("Solo",27);  
  6. sayHello("micky",29);  
  7. sayHello("Johnson",23);  
  8. ?>  
Output:
Hello Solo, you are 27 years old
Hello micky, you are 29 years old
Hello Johnson, you are 23 years old

Advantage of PHP Functions

Code Reusability: PHP functions are defined only once and can be invoked many times, like in other programming languages.
Less Code: It saves a lot of code because you don't need to write the logic many times. By the use of function, you can write the logic only once and reuse it.
Easy to understand: PHP functions separate the programming logic. So it is easier to understand the flow of the application because every logic is divided in the form of functions.