PHP Functions

PHP Functions give php language the real power.PHP has more than a 1000 functions that are built in.

PHP Functions Defined by the User

Apart from PHP functions that comes with this language,programmers can create their own functions that can be executed several in the code by just defining a function and calling it several where its needed.

How to Create PHP Functions defined by the user

To create a function,you need to declare it by using “function” keyword.


function nameOfTheFunction() {
    code to be run;

See Also:PHP  while Loops

Also note tha,just like Variables,a function name can start with letter or underscore.

Below example is a function that prints current date  and time using now();

The curly braces{} show the start and end of a function.

function dateTime() {
echo now();

dateTime (); // Function is called here


PHP Functions Arguments

PHP Functions needs sometimes needs  information.This Information is passed as argument which are variables.

Usually arguments are added after function name.A function can take several arguments and they are seperated by comma

Below is example of a function that takes two arguments,sums them up and outputs the total  of the two


function sumNumbers($num1,$num2)




echo"The Sum is".$total;






PHP Function That takes  one argument only.


function myName($name)

{   echo"My Name is is".$name;}





OutPut is “My Name is isEricMy Name is isJohnMy Name is isMellisa”

PHP Functions with Default Value Argument

PHP Functions can be created with a default argument value.Example below shows a function setWidth() with a default argument value.Once the function is called and no value is added,the function will use the default value.


function setWidth($minHeight=20)


echo"Minimum Width is".$minHeight;




setWidth();//Prints the default Value which is 20



PHP Functions  that Return values

A programmer may wish to use a value that is gotten after a function is called.To access the value outside the function and use it,return keyword is use.

Below example uses the value returned by a function to sum it up with another value.
function mutiply($y, $x) {
$total = $x*$y;
return $total;

echo "2 + 4 = " . sum(5, 10);//Output is 54
echo "5 +1  = " . sum(10, 10);//Output is 106



About the Author: Eric K

Kenyan Developer and Blogger with Interests in Java,Javascript,Node.js, Wordpress, Android, PHP and Making Money Online. Solving world problems through programming is my passion. Hire me: Email :