You are on page 1of 60

Outline

What Is Function ?

Create Function

Call Function

Parameters Functions

Function Returning Values

PHP Variable Scopes

Passing by Reference Vs Value

Pass Array To Function

What Is Function ?

In PHP we have tow type of functions :


1)

User-defined Function.

2)

Built-in Function.

User-defined Function : is the function created by user .

Built-in Function : is the function created by PHP , and ready to use.

The real power of PHP comes from its functions.

User-Defined Function

User-defined function is just a name we give to a block of code that can be executed whenever
we need it. A function will be executed by a call to the function. You may call a function from
anywhere within a page.

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)

Create a PHP Function


Begins with keyword function and then the space and then the
name of the function then parentheses() and then code block {}

function functionName()
{
//code to be executed;
}
Example

A simple function that writes my name when it is called:


<?php
function writeName()
{
echo lamya A Omar";
}

echo "My name is ";


writeName();
?>
Output:
My name is lamya A Omar

Call Function - Example


<?php
function myfunction()
{
echo Muneer Masadeh";
}
echo my name is ;
myfunction();
?>

Parameters Functions
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.
<?php
function myfunction($par1, $par2 ,..)
{
echo This is the first function with parameters to me ";
}
?>

PHP Functions - Adding parameters


Example 1
The following example will write different first names, but equal last name:
<html>
<body>
<?php
function writeName($fname)
{
echo $fname . " Omar.<br />";
}

echo "My name is ";


writeName(lamya");
echo "My sister's name is ";
writeName(Assma");
echo "My brother's name is ";
writeName("Ali");
?>
</body>
</html>

Output:
My name is lamya Omar.
My sister's name is Assma Omar.
My brother's name is Ali Omar.

Parameters Functions Call


<?php
function myname($firstName)

{
echo my name is ". $firstName . "!<br />";
}
myname(kalid");
myname("Ahmed");
myname(laith");
myname(muneer");
?>

Parameters Functions - Call


<?php
function myname($firstName, $lastName)
{
echo "Hello there ". $firstName ." ". $lastName ."!<br />";
}
myname(Kalid", Ali");
myname("Ahmed", Samer");
myname(Wael", Fadi");
myname(Muneer", " Masadeh");
?>

Parameters Functions - Call


<?php
function writeName($fname,$punctuation)
{
echo $fname . " Refsnes" . $punctuation . "<br />";
}
echo "My name is ";
writeName(muneer ",".");
echo "<br>My family's name is ";
writeName(" Masadeh ",,");
echo <br>I am Dr in ";
writeName(CS Department ",!");
?>

Function Returning Values


In addition to being able to pass functions information, you can also have
them return a value. However, a function can only return one thing, although
that thing can be any integer, float, array, string, etc. that you choose!

$myVar = somefunction(); Let's demonstrate this returning of a value by using a

simple function that returns the sum of two integers.


<?php
function mySum($numX, $numY)
{

return ($numX + $numY);


}
$myNumber = 0;
echo "Before call function, myNumber = ". $myNumber ."<br />";

// Store the result of mySum in $myNumber


$myNumber = mySum(3, 4);
echo "After call function, myNumber = " . $myNumber ."<br />";
?>

Function Returning Values Example


<?php
function factorial($number)
{
$ temp = 0;
if($number <= 1)
return 1;
$temp = $number * factorial($number - 1);
return $temp;
}
$ number = 4;
if ($number < 0)
echo "That is not a positive integer.\n";
else
echo $number . " factorial is: " . factorial($number);
?>

Function Returning Values Example

<?php
$n = 10;
echo " The sum is . sum($n) ;
function sum($a)
{
if ( $n <= 0 )
return 0;
else
return ($n + sum($n-1));
}
?>

PHP Variable Scopes


The scope of a variable is the part of the script where the
variable can be referenced/used.
PHP has four different variable scopes:
local

global
static
parameter

Local Scope
A variable declared within a PHP function is local and can only be
accessed within that function:

<?php
$x=5; // global scope
function myTest()
{
echo $x; // local scope
}
myTest();
?>

Local Scope
The script above will not produce any output because the echo statement
refers to the local scope variable $x, which has not been assigned a value
within this scope.
You can have local variables with the same name in different functions,
because local variables are only recognized by the function in which they
are declared.

Local variables are deleted as soon as the function is completed.

Global Scope
A variable that is defined outside of any function, has a
global scope.
Global variables can be accessed from any part of the script,
EXCEPT from within a function.
To access a global variable from within a function, use the
global keyword:

Global Scope
A variable that is defined outside of any function, has a global scope.
Global variables can be accessed from any part of the script, EXCEPT
from within a function.
To access a global variable from within a function, use the global keyword:
<?php
$x=5; // global scope
$y=10; // global scope
function myTest()
{
global $x,$y;
$y=$x+$y;
}
myTest();
echo $y; // outputs 15

?>

Global Scope

PHP also stores all global variables in an array called


$GLOBALS[index]. The index holds the name of the variable.
This array is also accessible from within functions and can be
used to update global variables directly.

The example above can be rewritten like this:


<?php
$x=5;
$y=10;
function myTest()
{
$GLOBALS['y']=$GLOBALS['x']+$GLOBALS['y'];
}
myTest();
echo $y;

?>

Static Scope
When a function is completed, all of its variables are
normally deleted. However, sometimes you want a local
variable to not be deleted.
To do this, use the static keyword when you first declare the
variable:

<?php

function myTest()
{
static $x=0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>

Static Scope
Then, each time the function is called, that variable will still
have the information it contained from the last time the

function was called.


Note: The variable is still local to the function.

Parameter Scope
A parameter is a local variable whose value is
passed to the function by the calling code.
Parameters are declared in a parameter list as
part of the function declaration:

<?php
function myTest($x)
{
echo $x;
}
myTest(5);
?>

Passing Variable to a fonction

You can pass a variable by Value to a function so the function cant modify the variable.

You can pass a variable by Reference to a function so the function can modify the variable.

<?php
$numX = 1;
function byvalue ($numX)
{
$numX = $numX + 1;
}
byvalue ($numX);
echo the change after send data by value = ". $numX ."<br />";
?>

Passing Variable By Reference

<?php

function byreference (&$numX)


{
$numX = $numX + 1;
}
byvalue ($numX);
echo the change after send data by Reference = ". $numX ."<br />";
?>

Passing Variable By Reference


<?php
function foo(&$var)
{
$var++;
}

$a=5;
echo foo($a); // $a is 6 here
?>

Passing Variable By Reference


<?php
function foo(&$var)
{
$var++;
return $var;
}
function &bar()
{
$a = 5;
return $a;
}
echo foo(bar());
?>

Passing Variable By Reference


<?php
$string = 'string';
function change($str) {

$str = 'str';
}
change(&$string);
echo $string;
?>

Example Chapter

Example
<?php
main();
function main()
{
$num1 = 10; $num2 = -6; $num3 = 2; $num4 = 1;
$op = "-";
echo "<ol>";
echo "<li> Expression is : $num1 $op $num2 $op $num3 $op $num4 = ".cal($num1,
$num2, $num3, $num4,$op)."</li>";

echo "<li> Max number between ( $num1 , $num2, $num3 , $num4 ) = ".maxs($num1, $num2,
$num3, $num4)."</li>";

Example
echo "<li> Min number between( $num1 , $num2, $num3 , $num4 ) = ".mins($num1,

$num2, $num3, $num4)."</li>";


echo "<li>Positive numbers between( $num1 , $num2, $num3 , $num4 ) </li>";
posi($num1, $num2, $num3, $num4);
echo "<br>";
echo "<li> Negative numbers between( $num1 , $num2, $num3 , $num4 ) </li>";
nega($num1, $num2, $num3, $num4);
echo "</ol>";
}

Example
function cal($num1 , $num2, $num3 , $num4,$op )
{
switch($op)
{
case "+": return ($num1 + $num2+ $num3 + $num4 ); break;
case "*": return ($num1 * $num2 * $num3 * $num4 ); break;
case "/": return ($num1 / $num2 / $num3 / $num4 ); break;

default : return ($num1 - $num2 - $num3 - $num4 ); break;


}
}

Example
function maxs($num1, $num2, $num3, $num4)

{
$max1 = $num1;
if ($num2 > $max1) {
$max1 = $num2;
}
if ($num3 > $max1) {
$max1 = $num3;
}
if ($num4 > $max1) {
$max1 = $num4;
}
return $max1; /* max is the largest value */
}

Example
function mins($num1, $num2, $num3, $num4)
{
$min1 = $num1;
if ($num2 < $min1) {
$min1 = $num2;
}
if ($num3 < $min1) {
$min1 = $num3;
}
if ($num4 < $min1) {
$min1 = $num4;
}
return $min1; /* max is the largest value */
}

Example
function posi($num1, $num2, $num3, $num4)
{
echo "<ol type='i'>";
$count = 0;
if($num1 > 0)
{
echo "<li>The $num1 is positive numbers </li>";
$count++;

}
if($num2 > 0)
{
echo "<li>The $num2 is positive numbers </li>";
$count++;
}

Example
if($num3 > 0)
{
echo "<li>The $num3 is positive numbers </li>";
$count++;
}
if($num4 > 0)
{
echo "<li>The $num4 is positive numbers </li>";

$count++;
}
echo "<li>The Total positive numbers is $count</li>";
echo "</ol>";
}

Example
function nega($num1, $num2, $num3, $num4)

{
$count = 0;
echo "<ol type='i'>";
if($num1 < 0)
{
echo "<li>The $num1 is negative numbers </li>";
$count++;
}
if($num2 < 0)

{
echo "<li>The $num2 is negative numbers </li>";
$count++;
}

Example
if($num3 < 0)

{
echo "<li>The $num3 is negative numbers </li>";
$count++;
}
if($num4 < 0)
{
echo "<li>The $num4 is negative numbers </li>";
$count++;
}

echo "<li>The Total negative numbers is $count</li>";


echo "</ol>";
}
?>

Q1.Suppose you want to write a function named


calculateSalesTotal() that calculates the sales total of a number
contained 3 parameters $Subtotal, $SalesTax, $Shipping).Note that
parameters receive their values when you call the function from
elsewhere in your program. create script that explain the previous
idea. Apply this function for three companies .
Q2. Create a code shows a switch statement contained within
a function. When the function is called, it is passed an argument
named $IraqiCity. Th e switch statement compares the contents
of the $IraqiCity argument to the case labels. If a match
is found, the citys state is returned and a break statement ends the
switch statement . If a match is not found, the value Iraq is
returned from the default label.

What is wrong with this example?can


we run this ?

<?php
function foo(&$var)
{
$var++;
}
function bar() // Note the missing &
{
$a = 5;
return $a;
}
foo(bar()); // Produces fatal error as of PHP 5.0.5, strict standards notice
// as of PHP 5.1.1, and notice as of PHP 7.0.0
foo($a = 5); // Expression, not variable
foo(5); // Produces fatal error
?>

PHP Functions
The real power of PHP comes from its functions.
functions.
Array functions
Calendar functions
Date functions
Directory functions
Error functions
Filesystem functions
Filter functions
FTP functions
HTTP functions
LibXML functions
Mail functions
Math functions
Misc functions
MySQL functions
SimpleXML functions
String functions
XML Parser functions
Zip functions

In PHP, there are more than 700 built-in

Function

Description

array()

Creates an array

array_change_key_case()

Changes all keys in an array to


lowercase or uppercase

array_count_values()

Counts all the values of an array

array_fill()

Fills an array with values

array_fill_keys()

Fills an array with values, specifying


keys

array_filter()

Filters the values of an array using a


callback function

array_flip()

Flips/Exchanges all keys with their


associated values in an array

array_merge()

Merges one or more arrays into one


array

array_multisort()

Sorts multiple or multi-dimensional


arrays

array_pop()

Deletes the last element of an array

array_push()

Inserts one or more elements to the


end of an array

Function

Description

array_unique()

Removes duplicate values from an array

array_unshift()

Adds one or more elements to the beginning of an array

array_values()

Returns all the values of an array

array_walk()

Applies a user function to every member of an array

array_walk_recursive()

Applies a user function recursively to every member of an


array

arsort()

Sorts an associative array in descending order, according to


the value

asort()

Sorts an associative array in ascending order, according to the


value

compact()

Create array containing variables and their values

count()

Returns the number of elements in an array

current()

Returns the current element in an array

each()

Returns the current key and value pair from an array

array_rand()

Returns one or more random keys from an


array

array_reduce()

Returns an array as a string, using a userdefined function

array_replace()

Replaces the values of the first array with the


values from following arrays

array_replace_recursive()

Replaces the values of the first array with the


values from following arrays recursively

array_reverse()

Returns an array in the reverse order

array_search()

Searches an array for a given value and


returns the key

array_shift()

Removes the first element from an array, and


returns the value of the removed element

array_slice()

Returns selected parts of an array

array_splice()

Removes and replaces specified elements of


an array

array_sum()

Returns the sum of the values in an array

Manipulating Arrays
Joining two arrays with array_merge()
array_merge() accepts two or more arrays and returns a merged
array combining all their elements .
In this example create two arrays ,joining the second to the first
and loop through the resultant third array :
$first=array( a, b , c);
$second=array(1,2,3);
$third= array_merge( $first , $second ) ;
foreach( $third as $val) {
print $val<br>;
}

Adding Multiple Variables to an Array with array_push


array_push accept s an array and number of further parameters, each of which is added to
the array , this function returns the total number of elements in the array .
Example 11
<html>

<head>
<title> passing references to f.variable </title>
</head>
<body>

<?php
$first=array( "a", "b", "c" );
$total=array_push($first, 1 , 2 , 3);
Print "there are $total elements in \$first <p>";

Foreach ( $total as $val)


{
print "$val <br>" ;
}

?>

there are 6 elements in $first


a
b
c
1
2
3

Removing the first element of an array within array_shift


array_shift Shift an element off the beginning of array
array_shift() shifts the first value of the array off and returns it, shortening
the array by one element and moving everything down. Note: This function
will reset() the array pointer of the input array after use.
Output
Example #1 array_shift() example
<?php
$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_shift($stack);
print_r($stack);
?>
array_unshift Prepend one or more elements to
the beginning of an array

Example #1 array_unshift() example


<?php
$queue = array("orange", "banana");
array_unshift($queue, "apple", "raspberry");
print_r($queue);
?>

Array (
[0] => banana
[1] => apple
[2] => raspberry
)
and orange will be assigned
to $fruit.

Array (
[0] => apple
[1] => raspberry
[2] => orange
[3] => banana
)

Description

Insert the element "blue" to an array:

<?php
$a=array("a"=>"red","b"=>"green");
array_unshift($a,"blue");
print_r($a);
?>

array

Required. Specifying an array

value1

Required. Specifies a value to insert

value2

Optional. Specifies a value to insert

Syntax
array_unshift(array,value1,value2,value3...)
<!DOCTYPE html>
<html>
<body>
<?php
$a=array("a"=>"red","b"=>"green");
print_r(array_unshift($a,"blue"));
?>
</body>
</html>

Compare between these two


codes

PHP array_combine() Function


The array_combine() function creates an array by using the elements from one
"keys" array and one "values" array.
Note: Both arrays must have equal number of elements!
Syntax
array_combine(keys,values);
Example
Create an array by using the elements from one "keys" array and one "values"
array:

<?php
$fname=array("Peter","Ben","Joe");
$age=array("35","37","43");
$c=array_combine($fname,$age);
print_r($c);
?>
Array ( [Peter] => 35 [Ben] => 37 [Joe] => 43 )

PHP array_chunk() Function


The array_chunk() function splits an array into chunks of new array

Example
Split an array into chunks of two:
<?php
$cars=array("Volvo","BMW","Toyota","Honda","Mercedes","Opel");
print_r(array_chunk($cars,2));
?>

bool shuffle ( array &$array )


This function shuffles (randomizes the order of the elements in) an
array.
Parameters
arrayThe array.
Return Values
Returns TRUE on success or FALSE on failure.
Example
Randomize the order of the elements in the array:
<?php
$my_array = array("red","green","blue","yellow","purple");
shuffle($my_array);
print_r($my_array);
?>

Example #2 shuffle() example


<?php
$numbers = range(1, 20);
shuffle($numbers);
foreach ($numbers as $number) {
echo "$number ";
}
?>
14 20 17 3 8 13 18 6 15 12 19 2 7 4 1 10 16 11 5 9
Example 3
Randomize the order of the elements in the array:
<?php
$my_array =
array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow","e"=>"purple"
);
shuffle($my_array);
print_r($my_array);
?>
Array ( [0] => blue [1] => yellow [2] => red [3] => purple [4] => green )

array_change_key_case
array_change_key_case Changes all keys in an array
Description
array array_change_key_case ( array $input [, int $case = CASE_LOWER ] )
Returns an array with all keys from input lowercased or uppercased. Numbered
indices are left as is. Parameters inputThe array to work on
caseEither CASE_UPPER or CASE_LOWER (default)
Return Values Returns an array with its keys lower or uppercased,
or FALSE if input is not an array. Errors/Exceptions
Throws E_WARNING if input is not an array.
Example
<?php
$input_array = array("FirSt" => 1, "SecOnd" => 4);
print_r(array_change_key_case($input_array, CASE_UPPER));
?>
The above example will output:
Array
[FIRST] => 1

[SECOND] => 4

array_unique

The array_unique() function removes duplicate values from an array. If two or more array values
are the same, the first appearance will be kept and the other will be removed.
Note: The returned array will keep the first array item's key type.

Description
array array_unique ( array $array [, int $sort_flags =SORT_STRING ] )
Takes an input array and returns a new array without duplicate values.
sort_flagsThe optional second parameter sort_flags may be used to modify the
sorting behavior using these values:
Sorting type flags:
SORT_REGULAR - compare items normally (don't change types)
SORT_NUMERIC - compare items numerically
SORT_STRING - compare items as strings
SORT_LOCALE_STRING - compare items as strings, based on the current locale.

Examples
Example #1 array_unique() example
<?php
$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input);
print_r($result);
?>

output:
Array ( [a] => green [0] => red [1] => blue )
Example #2 array_unique() and types
<?php
$input = array(4, "4", "3", 4, 3, "3");
$result = array_unique($input);
var_dump($result);
?>

array(2)
{
[0] => int(4)
[2] => string(1) "3
}

Array sorting functions


Function Behavior
asort()

Takes a single array argument. Sorts the key/value pairs by value but keeps the
key/value relationship the same

arsort()

Same as asort but sorts in descending order

ksort()

Takes a single array argument. Sorts the key/value pairs by key but maintains the
key/value relationships

krsort()

Same as ksort but in descending order

sort()

Takes a single array argument. Sorts the key/value pairs of an array by their values.
Keys may be renumbered to reflect the new ordering of the values

rsort()

Same as sort but in descending order

uasort()

Sorts key/value pairs by value using a comparison function as the second argument
which returns a negative number if its first argument is before the second, a positive
number if the first argument comes after the second, and 0 if the elements are the
same

uksort()

Same as uasort but sorts by the keys rather than the values

usort()

Same as uasort but key/value associations are not maintained

Sorting arrays
sorting numerically indexed arrays with sort()
$an_array = array ( x , w, a , o );

sort($an_array );
foreach ( $an_array as $var ){
print $var<br>;
}

sorting Associative array by value with asort()


$first = array ( first=>5 , second=>2 , third =>1 );
asort( $first );
third =1
foreach ( $first as $key => $val ){
second =2
print $key = $val <br>;
First =5
}

Deleting from arrays

Deleting an element from an array is just like


getting rid of an assigned variable calling the
unset() construct
unset($my_array[2]);
unset($my_other_array['yellow']);

Printing functions for arrays


(debugging)

bool print_r ( mixed expression [, bool return])


displays information about a variable in a way
that's readable by humans. If given a string,
integer or float, the value itself will be printed. If
given an array, values will be presented in a format
that shows keys and elements. Similar notation is
used for objects. print_r() and var_export() will
also show protected and private properties of
objects with PHP 5, on the contrary to var_dump().

Exercises
Using suitable PHP code to check
1-whether a given number is negative or positive .
2- student degree whether he pass or not taking in consideration that
Grade A if degree >=75,
Grade B if degree >=60,
Grade C if degree >=50,
Else fail.
3-create a program that the output "Have a nice weekend!" if the
current day is Friday, otherwise it will output "Have a nice day!.
4 Expenses is array(12 43 -3 54 67 78 89 12 -10 13 43 15 54 )
change it to array without any repeated element remove any
negative element then give the summation and the average.

Exercises
Imagine that you are an owner of a flower shop.
Using multidimensional arrays, create in table the
following in formation using php code:
Title
Price
Number
Rose
1.25
15
Daisy
0.75
25
Orchid 1.15
7
Insert new two kinds of flower with their prices
(Gardena p2.5 n44 & white flower p.25 n 22)

Exercises

Creates drop-down lists of days(1-31), months (112)and years(1999-2020). You can use this code
for registration form.
Simple function to sort an array by a specific key.
Maintains index association.(age)
id

First
name

Last name job

Age

address

11231

Akhen

Ali

Nurse

32

Dohok

11121

Laith

Ahmed

Worker

22

Dohok

Danny

Boss

45

Dohok

11033

You might also like