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.

Syntax

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.

<?php
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

<?php

function sumNumbers($num1,$num2)

{

$total=$num1+$num2;

 

echo"The Sum is".$total;

}

sumNumbers(12,14);

sumNumbers(12,14);

sumNumbers(12,14);

?>

PHP Function That takes  one argument only.

<?php

function myName($name)

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

myName("Eric");

myName("John");

myName("Mellisa")

?>

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.

<?php

function setWidth($minHeight=20)

{

echo"Minimum Width is".$minHeight;

}

 

setWidth(100);

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

setWidth(150);

?>

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.
<?php
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

My name is Eric.Am a software developer with skills in Php,Mysql, Java , Android,Node.js Above all, I have certification in Cisco Networking Associate (CCNA) and holds degree in Information Technology. Hire me: Email : kawi3462@gmail.com