Working with Functions in PHP

Oct 01, 2013, by admin

A functions is an independent block of code that performs a specific task and can be used more than once at a different points within the main program.

The real power of PHP comes from its functions.

In PHP, there are more than 700 built-in functions.

A function will be executed by a call to the function.

You may call a function from anywhere within a page.

Create a PHP Function

A function will be executed by a call to the function.

Syntax

function functionName()
{
code to be executed;
}

PHP function guidelines:

Give the function a name that reflects what the function does
The function name can start with a letter or underscore (not a number)

Example

A simple function that print city name when it is called:

<html>

<body>

<?php

function cityName()

{

echo “Delhi”;

}
echo “City Name is : “;  cityName();

?>

</body>

</html>

 

Output:

City Name is : Delhi

 

PHP Functions – Adding parameters

To add more functionality to a function, we can add parameters. A parameter is just like a variable.

Parameters are specified after the function name, inside the parentheses.

 

Example

The following example will write different city names:

<html>

<body>
<?php

function cityName($cityname)

{

echo $cityname . “<br />”;

}
echo “City name is “;  cityName(“Mumbai”);

?>
</body>

</html>

 

Output:

City name is Mumbai.

 

Example

The following function has two parameters:

<html>

<body>
<?php  function cityName($cityname,$country)

{

echo “City : “.$cityname . ” and Country :” . $country . “<br />”;

}
cityName(“Delhi”,”India”);

?>
</body>

</html>

 

Output:

City : Delhi and Country :India

 

PHP Functions – Return values

To let a function return a value, use the return statement.

Example

<html>

<body>

<?php

function getValue($value)

{

return $value;

}
echo “The Value is: “. getValue(100);

?>
</body>

</html>

 

Output:

The Value is:100