Function in PHP

PHP Functions

PHP function is group of code which execute as per our requirement.
PHP function is a code which get some value process it and returns output.
Function is a block of code that are used repeatedly in a program.
PHP language has many built-in ready made function which make easy and powerful programming.
PHP function name must be start with a letter or underscore.

PHP function types

  • built-in function
  • user defined function

User defined function syntax:

function functionname()
{
function code to be execute;
}

Create user defined function in php

In PHP we can easily create a user defined function. The PHP function create using function() keyword and all php code written in between two brackets { }.

PHP function does not execute while page load, we must call the function when we want to execute a function code.
Here, we create simple user defined function hellomsg() and print hello message in function then call the hellomsg() function after creating it.

Example of PHP function

<?php

function hellomsg() // create function
{
echo “Hello Meera”;
}

hellomsg(); // call function

?>

The output is :
Hello Meera


PHP function with Arguments

When we create a function with arguments, the argument is like a variable in function which assign value while calling a function.

When we call a function that time we need to assign parameter value and parameters value processed in function and returns a output.

PHP  function with arguments example

<?php

function addition($a,$b)
{

$sum=$a+$b;
echo “The sum = ” . $sum;
}

addition(5,7);
?>

The output is :
The sum = 12

In above php function example we create addition($a,$b) function with two arguments and here we print sum of two parameters value when function called. The function addition(5,7) call with two values 5 and 7, so output is sum  of  5 and 7 is equal to 12.


PHP function return value

PHP function return value we can call function and execute function code then use return keyword for return a value. Here we need to call function with variable for store output value.

<?php

function addition($a,$b)
{

$sum=$a+$b;

return $sum;

}

$answer = addition(5,7);
echo “The sum = ” . $answer;

?>

The output is:
The sum = 12

Leave a Reply

Your email address will not be published. Required fields are marked *

5 + 7 =


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">