Function in PHP

In PHP function is a block of code that can be reused many times. There are thousands of built-in functions in PHP that you can call directly within your PHP scripts to perform a specific task, like gettype(), print_r() etc. A function name can start with a letter or underscore.


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.


User-defined Functions :

Let's see the syntax to declare user-defined functions.
function functionName() {
      code to be executed;
}

Example :
<?php
function myMsg() {
echo "Welcome to Function in PHP";
}
myMsg(); /* call the function */
?>

Output :
Welcome to Function in PHP


Function Arguments : Information can be passed to functions through arguments. An argument is just like a variable. Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.

The following example has a function classStudents() with two argument ($name,$age).

Example :
<?php
function classStudents($name,$age){
    echo"$name is $age year old.<br>";
}
classStudents("Alokesh","23");
classStudents("Ashim","22");
classStudents("Bishnu","23");
classStudents("Mridul","21");
classStudents("Rahul","22");
?>

Output :
Alokesh is 23 year old.
Ashim is 22 year old.
Bishnu is 23 year old.
Mridul is 21 year old.
Rahul is 22 year old.

0 Comments