blog

Home / DeveloperSection / Blogs / Functions in PHP

Functions in PHP

Samuel Fernandes 1376 06-Jun-2016

In the previous post, we discussed the loop in php & form handling in php. In this article we will talk about function in php. 

A function is a piece of code which takes input in the form of parameter and process these parameter and returns a value .A function is  a block of statement that can be used anywhere in the program. PHP has more than 1000 built-in function like fopen(), fclose(),fread(),etc.

PHP gives you option to create your own function. These types of function are called user-defined functions.

User defined functions

It consists of two parts:-

  •   Creating a PHP function
  •   Calling a PHP function
Creating a function:

Creating your own PHP function is very easy. In the below example we will create a function named Myfunction().The opening braces ‘{‘ indicates the start of the function and closing braces ‘}’ indicates the end of the function.

<?php

//creating a php function
function Myfunction() // Myfunction is the name of the function(user defined). {
  echo("This is my First Function.");
}
  Myfunction(); //calling the Myfunction.
?>

  Output: 

This is my First Function

Passing Arguments in function

An argument is just like variable.  Information are passed to function through arguments. These arguments are specified after the name of the function in brackets. You can pass as many arguments as you can.

 Note:-These arguments must be separated by coma. Below is the example to show how arguments are passed:

<?php
function StudentName($student) //$student is the argument. It is a variable.
{
    echo "$student is a student of class 9.<br>";
}
StudentName("Ram");
StudentName("Neha");
StudentName("Kirti");
StudentName("Medha");
StudentName("Anshika");
?>

  Output: 

Ram is a student of class 9.
Neha is a student of class 9.
Kirti is a student of class 9.
Medha is a student of class 9.
Anshika is a student of class 9.
PHP default argument values:

Below example will show you how to use a default parameter:

<?php

function student($name = "Ram") {
    echo "The student name is : $name <br>";
}
student("shyam");
student(); // will use the default value of Ram
student("Neha");
student("Jagmeet");
?>

  Output: 

The student name is : shyam 
The student name is : Ram //Default value
The student name is : Neha
The student name is : Jagmeet 

 PHP function: Return values

To return value use return statement. Below is an example shows how to use return statement:

<?php
function add($a, $b) {
    $c = $a + $b;
    return $c;
}
echo "50 + 100 = " . add(50, 100) . "<br>";
echo "70 + 130 = " . add(70, 130) . "<br>";
echo "20 + 40 = " . add(20, 40);
?>

  Output: 

50 + 100 = 150
70 + 130 = 200
20 + 40 = 60

php php 
Updated 15-Mar-2018

Leave Comment

Comments

Liked By