Professional Documents
Culture Documents
What Is Function ?
Create Function
Call Function
Parameters Functions
What Is Function ?
User-defined Function.
2)
Built-in Function.
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.
Give the function a name that reflects what the function does
The function name can start with a letter or underscore (not a number)
function functionName()
{
//code to be executed;
}
Example
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 ";
}
?>
Output:
My name is lamya Omar.
My sister's name is Assma Omar.
My brother's name is Ali Omar.
{
echo my name is ". $firstName . "!<br />";
}
myname(kalid");
myname("Ahmed");
myname(laith");
myname(muneer");
?>
<?php
$n = 10;
echo " The sum is . sum($n) ;
function sum($a)
{
if ( $n <= 0 )
return 0;
else
return ($n + sum($n-1));
}
?>
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.
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
?>
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
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);
?>
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 />";
?>
<?php
$a=5;
echo foo($a); // $a is 6 here
?>
$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,
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;
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++;
}
<?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
Function
Description
array()
Creates an array
array_change_key_case()
array_count_values()
array_fill()
array_fill_keys()
array_filter()
array_flip()
array_merge()
array_multisort()
array_pop()
array_push()
Function
Description
array_unique()
array_unshift()
array_values()
array_walk()
array_walk_recursive()
arsort()
asort()
compact()
count()
current()
each()
array_rand()
array_reduce()
array_replace()
array_replace_recursive()
array_reverse()
array_search()
array_shift()
array_slice()
array_splice()
array_sum()
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>;
}
<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>";
?>
Array (
[0] => banana
[1] => apple
[2] => raspberry
)
and orange will be assigned
to $fruit.
Array (
[0] => apple
[1] => raspberry
[2] => orange
[3] => banana
)
Description
<?php
$a=array("a"=>"red","b"=>"green");
array_unshift($a,"blue");
print_r($a);
?>
array
value1
value2
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>
<?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 )
Example
Split an array into chunks of two:
<?php
$cars=array("Volvo","BMW","Toyota","Honda","Mercedes","Opel");
print_r(array_chunk($cars,2));
?>
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
}
Takes a single array argument. Sorts the key/value pairs by value but keeps the
key/value relationship the same
arsort()
ksort()
Takes a single array argument. Sorts the key/value pairs by key but maintains the
key/value relationships
krsort()
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()
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()
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>;
}
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
Age
address
11231
Akhen
Ali
Nurse
32
Dohok
11121
Laith
Ahmed
Worker
22
Dohok
Danny
Boss
45
Dohok
11033