You are on page 1of 9

1.

Functions
A function is a subroutine that allows you to perform a set of instructions by simply
calling this function in the body of the main program. The functions execute in several parts of
the program a series of instructions, this allows simplicity of the code and therefore a minimum
program size.

PHP has a large collection of internal or built-in functions that you can call directly in
your PHP scripts to perform a specific task, like gettype ( ), print_r (), var_dump , etc.

1.1.Built-in PHP functions

For a complete reference and examples of the built-in functions. Please see the PHP
References section for a complete list of useful PHP built-in functions, PHP Functions
Reference.

1.2.PHP user functions or PHP user-defined functions

In addition to built-in functions, PHP also allows you to define your own functions. It's
a way to create reusable packages of code that perform specific tasks and can be stored and
maintained separately from the main program. Here are some benefits of using these features:

- Functions reduce code repetition in a program: Functions allow you to extract the
most used blocks of code into a single component. You can now perform the same task
by calling this function wherever you want in your script without having to copy and
paste the same block of code repeatedly.
- Functions make code much easier to maintain: Since a function created once can be
used multiple times, any changes made inside a function are automatically implemented
wherever it is applied without touching to different files.
- Functions make it easier to eliminate errors: When the program is divided into
functions, if an error occurs, you know exactly which function is causing the error and
where to find it. Therefore, fixing errors becomes much easier.
- Functions can be reused in other applications : As a function is separated from the
rest of the script, it is easy to reuse the same function in other applications by simply
including the php file containing these functions.

The following section shows how to easily define your own function in PHP.
1.3.Create and use functions in PHP
The basic syntax for creating a custom function can be given as follows: A function will
be executed by a call to the function.

Syntax:

function FunctionName ()

code to execute;

PHP function directives:


- Give the function a name that reflects what the function does so you know what function
it is if you want to use it.
- The function name can start with a letter or an underscore
- Function name cannot start with a number

Example :
A simple function that writes my name when called I named it writeName :

<! DOCTYPE html>

<html> _ _

< head lang =" en ">

< meta charset ="utf-8">

< title > PHP function creation</ title >

<? php

// Creation of the function

function writeName ()

echo "Joe the GOOD";

?>
</head> _ _

< body >

<p> _ _

<? php

// here we call the function

echo "my name is: ";

writeName ();

?>

</p>

</body>

</html>

The result is the following:


My name is: Good Joe
1.4.PHP functions with parameters
You can add parameters when you define your function to accept input values at
runtime. Parameters work like replacement variables in a function; they are replaced at runtime
by the values (called arguments) supplied to the function at the time the function is called.

Syntax:

function Name_function (parameter1, parameter2, parameter3 ...)

code to execute;

Example 1 : The following example will write different first names for the same last
name:

<html> _ _

< body >


<? php

// fname is a parameter for the writeName function

function writeName ($ fname )

echo $ fname . "the GOOD< br />";

echo "My name is: ";

writeName ("Joe"); // here the function parameter is Joe

echo "My sister's name is: ";

writeName ("Jalila"); //here the function parameter is Jalila

echo "My brother's name is: ";

writeName ( "Jim"); // here the function parameter is Jim

?>

</body>

</html>

The result is the following:


My name is: Good Joe.
sister 's name is: Jalila le BON.
My brother's name is: Good Jim.
Example 2 : The following function has two parameters:
You can set as many parameters as you want. However, for each parameter you specify, a
corresponding argument must be passed to the function when it is called.

<html> _ _
< body >
<? php
function writeName ($ fname , $ detail )
{
echo $ fname . "the GOOD is ". $ detail . "< br /> ";
}

writeName ( "Joe", "me");

writeName ( "Jalila", "my sister");

writeName ( " Jim","my brother");


?>
</body>
</html>
The result is the following:
Joe the GOOD is me
Jalila le BON is my sister
Jim the GOOD is my brother
Example 3 The same example but with the use of a loop:
<html> _ _
< body >
<? php
$x= array ("Joe", "Jalila", "Jim");
$y= array ("me", "my sister", "my brother");
function writeName ($ fname , $ detail )
{
echo $ fname . "the GOOD is". $ detail . "< br /> ";
}
for ($i=0; $i<=2; $i++)
{
writeName ($x[$i] ,$y[$i]);
}
?>
</body>
</html>
The result is the following:
Joe the GOOD is me
Jalila le BON is my sister
Jim the GOOD is my brother
1.5.PHP functions: return values
To let a function return a value, we use the statement return.
Example :
<html> _ _
< body >
<? PHP
function append ($x, $y)
{
$total=$x+$y;
return $ total;
}
$x= 1;$ y=16;
echo $x." + ".$y. " = " . add (1.16);
?>
</body>
</html>
The result is the following:
1 + 16 = 17
2. Arrays _
An array is a special variable, which can store multiple values in a simple, single
variable . If you have a list of items (a list of car names, for example), storing cars in simple
variables might look like this :
$cars1= "Renault";

$cars2= "Volvo";

$cars3= "BMW";

However, what if you want to loop around and find a specific car? What if you didn't
just have 3 cars, but 300? The best solution here is to use an array !

An array can hold all your variable values under a single name. And you can access the
values by referring to the name of the array .

Each element in the array has its own index so that it can be easily accessed. In PHP,
there are three types of arrays :

- numeric array : An array with a numeric index


- associative array : An array where each identification key is associated with a value
- multidimensional array : An array containing one or more arrays
2.1. digital arrays
A numeric array stores each array element with a numeric index. There are two methods
to create a numeric array .

In the following example the indexes are automatically assigned (the index starts at 0):

$cars= array ("Renault", "Volvo", "BMW", "Toyota" );

In the following example we assign the index manually:


$cars[0] = "Renault";
$cars[1] = "Volvo";
$cars[2] = "BMW";
$cars[3] = "Toyota";
Example
In the following example you access values by referring to the name and index of the
array :

<? PHP

$cars[0] = "Renault";

$cars[1] = "Volvo";
$cars[2] = "BMW";

$cars[3] = "Toyota";

echo $cars[1]. ", ". $cars[2]." and ".$ cars[3]. "are not French cars.";

?>

The result is the following:


Volvo, BMW and Toyota are not French cars.
2.2. associative array
An associative array , each identification key is associated with a value. To store data
whose value subjects are specific, a numeric array is not always the best way to do it.

With associative arrays we can use values as keys and assign values to them.

Example 1

In this example we assume that we have a member's area in our site, visitors register to
become a member. We want to store data about a member who logs into his member's area:

for example (login, password, email, status)

$member = array ("login" =>toutou, " pass " =>abcd30, "mail"


=>toutou@serveur.com, "status" =>basic);

Example 2

This example is the same as example 1, but in a different way:

$member["login"] = "doggie";
$member[" pass "] = "abcd30";
$member["mail"] = "toutou@serveur.com";
$member["status"] = "basic";
Identification keys can be used in php code :

<? PHP
$member["login"] = "doggie";
$member[" pass "] = "abcd30";
$member["mail"] = "toutou@serveur.com";
$member["status"] = "basic";
echo "hello: ". $member ["login"]. "your password is: ". $member[" pass "]."
";
echo "and your email address is: ". $member ["email"]. "your status is: ".
$member["status" ];
?>
2.3.Multidimensional arrays
In a multidimensional array, each element in a main array can also be an array . And
each element in the secondary array can also be an array , and so on.

Example

In this example we create a multidimensional array, with automatically assigned


identification keys:

$families = array

("Griffin " => array (" Peter","Lois","Megan "),

"Swamp" => array ("Glenn"),

"Brown " => array (" Cleveland","Loretta","Junior ")

);

Example 2 Try the following code:

<? php
$families = array
("Griffin " => array (" Peter","Lois","Megan "),
"Swamp" => array ("Glenn"),
"Brown " => array (" Cleveland","Loretta","Junior ")
);
echo $families ["Griffin"] [2]." is part of the Griffin family?
";
echo $families ["Brown"] [0]." is part of Brown's family?" ;
?>

You might also like