Functions in PHP

PHP Functions: ( )

Just like any other language PHP also, provides the function facility.

What are functions?

To do repetitive, complex or out of sequence one time calculation, we create a function. whenever we need to do the certain calculation we just make a call to the function.

Functions are widely used concepts present in almost every scripting language. They make the code look simpler and easy to maintain.

The PHP functions are basically of two types.

  • User Defined functions
  • Inbuilt functions

Lets us now learn about these functions one by one.


User defined functions

The PHP functions can take parameters and return values also. We will learn about them with examples. The syntax of a function is as given below.


function function_name($parameter1, $parameter2){
PHP Statements;
return $return_value;
}

The following example will make the things clearer.


echo get_mean(1,2,3);

function get_mean($x,$y,$z){
return ($x+$y+$z)/3;
}

The above example will output the value 2.

Note that the scope of the variables defined a function is limited to the function itself unless you
declare them as global variables. So, If you write and use a function like this


$a=1;
$b=2;
$c=3;
$mean = get_mean($a,$b,$c);
echo $mean;

function get_mean($x,$y,$z){
($x+$y+$z)/3;
}

and expect the output to be 2, It will not happen. You will have to write a return statement inside the function to retrieve the value of the expression outside the function!


PHP Inbuilt functions

PHP provides several inbuilt functions for common calculations. You have to do nothing to use these functions. If the corresponding module is loaded in your web server, you can just use these functions like you wrote them yourselves.

Some common PHP functions are time(), date(), rand();trim(); str_replace() etc. We will learn more about the common functions in the PHP functions section.