0% found this document useful (0 votes)
32 views76 pages

module 3

This document covers PHP arrays and user-defined functions, detailing their types, usage, and manipulation techniques. It explains one-dimensional, associative, and multidimensional arrays, as well as functions for visualizing and sorting arrays. Additionally, it discusses the concept of functions in PHP, including user-defined and predefined functions, variable scope, and the use of static variables.

Uploaded by

tjzbay13
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views76 pages

module 3

This document covers PHP arrays and user-defined functions, detailing their types, usage, and manipulation techniques. It explains one-dimensional, associative, and multidimensional arrays, as well as functions for visualizing and sorting arrays. Additionally, it discusses the concept of functions in PHP, including user-defined and predefined functions, variable scope, and the use of static variables.

Uploaded by

tjzbay13
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 76

Applications Development and

Emerging Technologies
MODULE 3
PHP Arrays and User Defined
Functions
PHP Arrays and User Defined Functions

Objectives
• To know the different approach of using arrays in PHP.
• To be familiar with using print_r function and var_dump
function for array inspection.
• To use PHP lazy function foreach to iterate through array
elements.
• To implement one dimensional and multi-dimensional in the
program.
• To know what is associative array in PHP.
• To use different predefined functions in manipulating array
elements.
• To defined what is function and to use function keyword in
declaring function in PHP.
• To create a user defined function using different approach.
PHP Arrays and User Defined Functions

Objectives (continue)
• To know use variables that is globally declared and locally
declared.
• To create static variables that can be used in accumulating
data every time the function calls.
PHP Arrays
PHP Arrays and User Defined Functions

Array
is used to aggregate a series of similar items together, arranging and
dereferencing them in some specific way.

• Each member of the array index references a corresponding


value and can be a simple numerical reference to the value’s
position in the series, or it could have some direct correlation to
the value.
• PHP array does not need to declare how many elements that
the array variable have.
• Array index in PHP can be also called as array keys.
• Array can be used as ordinary array same as in C and C++
arrays.
PHP Arrays and User Defined Functions

Array: one dimensional

Example: Code 1 Example: Code 2

Example: Code 3 Output:


PHP Arrays and User Defined Functions

Array: Functions for visualizing arrays

print_r() function
short for print recursive. This takes an argument of any type
and prints it out, which includes printing all its parts
recursively.

var_dump() function
is same as the print_r function except that it prints additional
information about the size and type of the values it discovers

print_r() and var_dump() functions are commonly used


for debugging. The point of this of these functions is to help
you visualize what’s going on with compound data structures
like arrays.
PHP Arrays and User Defined Functions

Array: Functions for visualizing arrays

Example: using print_r() Output:

Example: using var_dump() Output:


PHP Arrays and User Defined Functions

Array: Looping through array elements

foreach() function
is a statement used to iterate or loop through the element in an
array. With each loop, a foreach statement moves to the next
element in an array.

foreach statement
specify an array expression within a set of parenthesis
following the foreach keyword.

Syntax
PHP Arrays and User Defined Functions

Array: Looping through array elements

$arr The name of the array that you’re walking through.


$key The name of the variable where you want to store
the key. (optional)
$value The name of the variable where you want to store
the value

Example: Output:
PHP Arrays and User Defined Functions

Array: Looping through array elements

Example:

Output:
PHP Arrays and User Defined Functions

Arrays: Multidimensional arrays Output:

Example:
PHP Arrays and User Defined Functions

Arrays: Sorting

Function Description
sort($array) Sorts by value; assign new numbers as the keys
rsort($array) Sorts by value in reverse order; assign new number
as the keys
asort($array) Sorts by value; keeps the same key
arsort($array) Sorts by value in reverse order; keeps the same key
ksort($array) Sorts by key
krsort($array) Sorts by key in reverse order
usort($array, Sorts by a function
functionname)
PHP Arrays and User Defined Functions

Arrays: Sorting

Example: Output:
PHP Arrays and User Defined Functions

Arrays: Sorting

Example: Output:
PHP Arrays and User Defined Functions

Arrays: Sorting

Example: Output:
PHP User Defined Functions
PHP Arrays and User Defined Functions

Functions
is a group of PHP statements that performs a specific task. Functions are
designed to allow you to reuse the same code in different locations.

User defined functions


functions that are provided by the user of the program.

Predefined functions
functions that are built-in into PHP to perform some standard operations
PHP Arrays and User Defined Functions

Functions: User defined functions

Syntax
function name(param){
//code to be executed by the function
}

Where
function – is the keyword used to declare a function
name – is the name of the function or function
identifier
param – is the formal parameters of the function.
Parameter must follow the rule of naming
dentifier.
PHP Arrays and User Defined Functions

Functions: Function with no parameters

Example: Output:
Slide 22
PHP Arrays and User Defined Functions

Functions: Function with parameters

Example: Output:
PHP Arrays and User Defined Functions

Functions: Function that returns a value

Example: Output:
PHP Arrays and User Defined Functions

Functions: Nested function

Example:

Output:

Example: Output:
PHP Arrays and User Defined Functions

Functions: Variable scope

Global Variables
is one that declared outside a function and is available to all
parts of the program.

Local Variables
is declared inside a function and is only available within the
function in which it is declared.

Static Variables
is used to retain the values calls to the same function.
PHP Arrays and User Defined Functions

Functions: using variables

Example: Output:

Example: Output:
PHP Arrays and User Defined Functions

Functions: using variables

Example: Output:

Example: Output:
PHP Arrays and User Defined Functions

Functions: using variables

Example:

Output:
An introduction to PHP web programming

Summary
• Array is used to aggregate a series of similar items together.
• Array index references a corresponding value.
• Array index can be simple numerical or have some direct
correlation to the value.
• Array index is also known as Array Keys.
• print_r function is used to print the array structure.
• var_dump function is same as print_r function except it adds
additional information about the data of each element.
• The foreach statement is use to iterate through the element in an
array.
• Using foreach statement you can display both the keys and value
of each element in the array.
• PHP provides functions for array manipulation such as sort(),
rsort(), asort(), arsort(), ksort(), krsort(), and usort() functions.
An introduction to PHP web programming

Summary (continue)
• sort(), asort(), and ksort() functions are used to sort elements in the
array in ascending order.
• rsort(), arsort(), and krsort() functions are used to sort elements in
the array in descending order.
• sort() and rsort() does not maintain its index reference for each
values.
• asort(), ksort(), arsort(), and krsort() maintains its reference for each
values.
• asort() and arsort() used to sort elements by values.
• ksort() and krsort() used to sort elements by keys.
• Functions is a group of PHP statements that performs a specific
task.
• Functions can be user defined generally defined by the user of the
program and predefined that are build in using libraries.
An introduction to PHP web programming

Summary (continue)
• You use functions in different ways. Function can only do
something without passing values. You can pass values to a
function and you can ask functions to return a value.
• function keyword is used in PHP to declare a function.
• A function that is declared inside a function is said to be hidden.
• To gain access to a variable that is outside from the function we
use the global keyword.
• We use static keyword to declare a variable inside a function that
will act as accumulator variable this will let the program remember
the last value of the variable that was used.
What is Array?
An array is a data structure that stores one or more similar type of values in a single
value. For example if you want to store 100 numbers then instead of defining 100
variables its easy to define an array of 100 length.
There are three different kind of arrays and each array value is accessed using an ID c
which is called array index.
• Numeric array − An array with a numeric index. Values are stored and
accessed in linear fashion.
• Associative array − An array with strings as index. This store element values in
association with key values rather than in a strict linear index order.
• Multidimensional array − An array containing one or more arrays and values
are accessed using multiple indices
NOTE − Built-in array functions is given in function reference PHP Array Functions
Numeric Array
These arrays can store numbers, strings and any object but their index will be
represented by numbers. By default array index starts from zero.
Example
Following is the example showing how to create and access numeric arrays.
Here we have used array() function to create array. This function is explained in
function reference.
<html>
<body>

<?php
/* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5);

foreach( $numbers as $value ) {


echo "Value is $value <br />";
}

/* Second method to create array. */


$numbers[0] = "one";
$numbers[1] = "two";
$numbers[2] = "three";
$numbers[3] = "four";
$numbers[4] = "five";

foreach( $numbers as $value ) {


echo "Value is $value <br />";
}
?>

</body>
</html>

This will produce the following result −


Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
Value is one
Value is two
Value is three
Value is four
Value is five
Associative Arrays
The associative arrays are very similar to numeric arrays in term of functionality but
they are different in terms of their index. Associative array will have their index as string
so that you can establish a strong association between key and values.
To store the salaries of employees in an array, a numerically indexed array would not
be the best choice. Instead, we could use the employees names as the keys in our
associative array, and the value would be their respective salary.
NOTE − Don't keep associative array inside double quote while printing otherwise it
would not return any value.
Example
<html>
<body>

<?php
/* First method to associate create array. */
$salaries = array("mohammad" => 2000, "qadir" => 1000,
"zara" => 500);

echo "Salary of mohammad is ". $salaries['mohammad'] .


"<br />";
echo "Salary of qadir is ". $salaries['qadir']. "<br />";
echo "Salary of zara is ". $salaries['zara']. "<br />";

/* Second method to create array. */


$salaries['mohammad'] = "high";
$salaries['qadir'] = "medium";
$salaries['zara'] = "low";
echo "Salary of mohammad is ". $salaries['mohammad'] .
"<br />";
echo "Salary of qadir is ". $salaries['qadir']. "<br />";
echo "Salary of zara is ". $salaries['zara']. "<br />";
?>

</body>
</html>

This will produce the following result −


Salary of mohammad is 2000
Salary of qadir is 1000
Salary of zara is 500
Salary of mohammad is high
Salary of qadir is medium
Salary of zara is low
Multidimensional Arrays
A multi-dimensional array each element in the main array can also be an array. And
each element in the sub-array can be an array, and so on. Values in the multi-
dimensional array are accessed using multiple index.
Example
In this example we create a two-dimensional array to store marks of three students in
three subjects −
This example is an associative array, you can create numeric array in the same
fashion.
<html>
<body>

<?php
$marks = array(
"mohammad" => array (
"physics" => 35,
"maths" => 30,
"chemistry" => 39
),

"qadir" => array (


"physics" => 30,
"maths" => 32,
"chemistry" => 29
),

"zara" => array (


"physics" => 31,
"maths" => 22,
"chemistry" => 39
)
);

/* Accessing multi-dimensional array values */


echo "Marks for mohammad in physics : " ;
echo $marks['mohammad']['physics'] . "<br />";

echo "Marks for qadir in maths : ";


echo $marks['qadir']['maths'] . "<br />";

echo "Marks for zara in chemistry : " ;


echo $marks['zara']['chemistry'] . "<br />";
?>

</body>
</html>

This will produce the following result −


Marks for mohammad in physics : 35
Marks for qadir in maths : 32
Marks for zara in chemistry : 39
Arrays

What is an Array?
• An array is an ordered collection of elements. Each element has a value, and is
identified by a key. Each array has its own unique keys.
• The keys can be either integer numbers or strings.

The array() Construct


• Calling The array() construct creates a new array. Passing a series of values to the
array() construct will populate the new created array with these values.
• Each one of the values will automatically get an index number, that will be its key.
• We can alternatively specify both the keys and the values.

Examples:

<?php
$vec_1 = array(2,4,5);
echo "<BR><BR>"."simple array of numbers";
for($i=0; $i<3; $i++)
{
echo "<BR>".$vec_1[$i];
}
?>

<?php
$vec_1 = array("moshe","david","john");
echo "simple array of strings";
for($i=0; $i<3; $i++)
{
echo "<BR>".$vec_1[$i];
}
?>

<?php
$vec_1 = array(100=>"moshe",101=>"david",102=>"john");
echo "simple array of strings and their keys";
echo "<BR>".$vec_1[100];
echo "<BR>".$vec_1[101];
echo "<BR>".$vec_1[102];
?>
<?php
$vec_1 = array("m"=>"moshe","d"=>"david","j"=>"john");
echo "simple array of strings and their keys";
echo "<BR>".$vec_1["m"];
echo "<BR>".$vec_1["d"];
echo "<BR>".$vec_1["j"];
?>

The var_dump() Function


• Prints out the content of a composite value (e.g. array) together with the data type of
each one of the values.

<?php
$vec = array(2,4,5,123,2221,”sda”);
var_dump($vec);
?>

• Using var_dump() function we can print out more than one array.

<?php
$vec_1 = array(2,4,5,123,2221);
$vec_2 = array(24,442,32,84,110);
$vec_3 = array(10,20,30,40,50);
var_dump($vec_1,$vec_2,$vec_3);
?>

The print_r() Function


• Prints out the contents of a composite value (e.g. array).
• Unlike var_dump(), this function cannot print out more than one array.

<?php
class Rectangle {}
$vec_1 = array(2,4,5,123,”fofo”,new Rectangle());
print_r($vec_1);
?>
Array Inner Structure
• PHP arrays behave like ordered map. As such, they allow various possibilities:

PHP arrays can be used to simulate different types of structures (e.g. map, queue, stack etc...).

PHP arrays can have unique keys, both numeric and textual. When using numeric ones, they
don't need to be sequential.

Multi Dimensional Arrays


• A multidimensional array is an array that each one of its elements is another array.

<?php
$matrix = array();
$matrix[0] = array("a","b");
$matrix[1] = array("c","d");
echo $matrix[0][0];
echo $matrix[0][1];
echo $matrix[1][0];
echo $matrix[1][1];
?>

The list() Construct


• The list() construct provides a short cut for an automatic assignment of an array's
elements into individual variables.

<?php
$info = array('moshe', 'david', 'michael','john');
list($operation_manager, $marketing_manager, ,$finance_manager) = $info;
echo "<BR>operation department manager is $operation_manager";
echo "<BR>finance department manager is $finance_manager";
echo "<BR>marketing department manager is $marketing_manager";
?>

<?php
$vec = [2=>"dave",1=>"ron",0=>"chen",3=>"ran"];
list($a,$b,$c) = $vec;
echo "<br>a=$a";
echo "<br>b=$b";
echo "<br>c=$c";
?>
• As of PHP 5.5 we can use the list construct together with the foreach loop.

<?php
$matrix = [
["haim", "michael", 344537565],
["mosh", "solomon", 452234343],
["ron","kalmon",453234234]
];
foreach ($matrix as list($fname, $lname,$id))
{
echo "fname:$fname lname:$lname id:$id ";
}
?>

The '+' Operator


• Using the + operator on two arrays we will get a union of the two arrays.
• Union of two arrays will include a union of the keys each one of the two arrays have and
the values assigned with each one of them.

<?php
$vec_1 = array(1,2,3);
$vec_2 = array(3,4,5,6);
$vec_3 = $vec_1 + $vec_2;
var_dump($vec_3);
?>

The '==' and '===' Operators


The '==' operator (equality) returns true if the following condition fulfills:

1. The two arrays contain the same elements.

The '===' operator (non identity) returns true if each one of the following two conditions fulfills:
1. The two arrays contain the same elements.

2. The two arrays have their identical elements in the same position.

<?php
//$a = ['a'=>'avodado','b'=>'bamba','c'=>'calco'];
//$b = ['b'=>'bamba','a'=>'avodado','c'=>'calco'];
$a = [123,455,323];
$b = [323,123,455];
if($a==$b)
{
echo "a and b equal";
}
else
{
echo "a and b not equal";
}
?>
Result: a and b not equal

The '!=' and '!==' Operators


The '!=' operator (inequality) returns true if the following condition doesn't fulfill:

1. The two arrays contain the same elements.

The '!==' operator (non identity) returns true if at least one of the following two conditions doesn't
fulfill:

1. The two arrays contain the same elements.

2. The two arrays have their identical elements in the same position.

Example

<?php
$vec_1 = array(1,2,3);
$vec_2 = array(1,2,3);
$vec_3 = array(0=>1, 1=>2, 2=>3);
$vec_4 = array(12=>1, 3=>2, 4=>3);
$vec_5 = array(1=>2, 0=>1, 2=>3);
var_dump($vec_1==$vec_2); //true
var_dump($vec_1===$vec_2); //true
var_dump($vec_1!=$vec_2); //false
var_dump($vec_1!==$vec_2); //false
echo "<BR>";
var_dump($vec_2==$vec_3); //true
var_dump($vec_2===$vec_3); //true
var_dump($vec_2!=$vec_3); //false
var_dump($vec_2!==$vec_3); //false
?>
Example

<?php
echo "<BR>";
var_dump($vec_2==$vec_4); //false
var_dump($vec_2===$vec_4); //false
var_dump($vec_2!=$vec_4); //true
var_dump($vec_2!==$vec_4); //true
echo "<BR>";
var_dump($vec_2==$vec_5); //true
var_dump($vec_2===$vec_5); //false
var_dump($vec_2!=$vec_5); //false
var_dump($vec_2!==$vec_5); //true
?>

The count() Function


Calling the count() function on a given array returns its size.

<?php
$vec = array(1,2,3,4,5,6,7,8);
echo count($vec);
?>

The is_array() Function


Calling the is_array() function on a variable returns true if that variable holds an array, and false
if isn't.

<?php
$vec_1 = array(1,2,3,4,5,6,7,8);
$vec_2 = 123;
if(is_array($vec_1))
echo "<BR>vec_1 is an array";
else
echo "<BR>vec_1 is not an array";
if(is_array($vec_2))
echo "<BR>vec_2 is an array";
else
echo "<BR>vec_2 is not an array";
?>
The isset() Function
Calling the isset() function can tell us if a specific key already exists in our array... or not.

<?php
$vec = array('a'=>1,'b'=>2,'c'=>3);
if(isset($vec['a'])) echo "<BR>'a' key exists";
if(isset($vec['b'])) echo "<BR>'b' key exists";
if(isset($vec['c'])) echo "<BR>'c' key exists";
if(isset($vec['d'])) echo "<BR>'d' key exists";
if(isset($vec['e'])) echo "<BR>'e' key exists";
?>

The array_key_exists() Function


Calling the array_key_exists() function can tell us if a specific key already exists in our array... or
not.

<?php
$vec = array('a'=>1,'b'=>2,'c'=>3);
if(array_key_exists('a',$vec)) echo "<BR>'a' key exists";
if(array_key_exists('b',$vec)) echo "<BR>'b' key exists";
if(array_key_exists('c',$vec)) echo "<BR>'c' key exists";
if(array_key_exists('d',$vec)) echo "<BR>'d' key exists";
if(array_key_exists('e',$vec)) echo "<BR>'e' key exists";
?>

The isset() function doesn't return true for array keys that were set together with null as its
value.

The array_key_exists() function does return true in those cases.

The in_array() Function


Calling the in_array() function checks if a given value exists in a given array.

<?php
$vec = array('a','b','c','d','f','g','h');
if(in_array('a',$vec)) echo "<BR>'a' exists";
else echo "<BR>'a' doesn't exist";
if(in_array('b',$vec)) echo "<BR>'b' exists";
else echo "<BR>'b' doesn't exist";
if(in_array('c',$vec)) echo "<BR>'c' exists";
else echo "<BR>'c' doesn't exist";
if(in_array('d',$vec)) echo "<BR>'d' exists";
else echo "<BR>'d' doesn't exist";
if(in_array('e',$vec)) echo "<BR>'e' exists";
else echo "<BR>'e' doesn't exist";
?>

The array_flip() Function


This function returns a new array, which is the result of inverting value of each element with its
key.

<?php
$vec_1 = array("a","b","c","d","f","g","h");
echo "<BR>before...<BR>";
var_dump($vec_1);
$vec_2 = array_flip($vec_1);
echo "<BR>after...<BR>";
var_dump($vec_2);
?>

The array_reverse() Function


This function returns a new array, which is the result of reversing the order of a given one.

<?php
$vec_1 = array("a","b","c","d","f","g","h");
echo "<BR>before...<BR>";
var_dump($vec_1);
$vec_2 = array_reverse($vec_1);
echo "<BR>after...<BR>";
var_dump($vec_2);
?>
.

The Array Pointer


When going over the elements, there is a pointer that points at the current element.

reset() resets the pointer to the array initial position.

next() moves the pointer to the next element.

prev() moves the pointer to the previous element.

current() gets the current element's value.


key() gets the current element's key.

<?php
$vec = array("a","b","c","d","f","g","h");
reset($vec);
while(key($vec)!==null)
{
echo key($vec)." is the key and ".current($vec)." is the value<BR>";
next($vec);
}
?>

The foreach Construct


The foreach construct allows traversing an array from start

The foreach Construct


<?php
$vec = array('moshe','david','michael','mike');
foreach($vec as $key_var => $value_var)
{
echo "<BR>$key_var : $value_var";
}
?>
The foreach Construct
The following is an alternative syntax for using the foreach

<?php
$vec = array('moshe','david','michael','mike');
foreach($vec as $value_var)
{
echo "<BR>$value_var";
}
?>

The array_combine() Function


The array_combine(array $keys, array $values) function receives two arrays and creates a new
array. The keys are the values of the first array elements. The values are the values of the
second array elements.

<?php
$values_vec =
array('moshe','david','michael','mike');
$keys_vec = array('mosh','dav','mich','mik');
$vec = array_combine($keys_vec,$values_vec);
print_r($vec);
?>
The array_walk() Function
The array_walk(array &$vec, callback $function) function goes over each one of the array's
elements and calls the function on each one of them.

The function should include two parameters. The first is the array's value and the second is the
array's key.

The array_walk has a third optional parameter ($user_data). If it is passed then it would be
passed as an argument to the function that is called on each one of the elements.

<?php
$cars = array("T" => "Toyota", "M" => "Mazda", "S" => "Suzuki", "Y" => "Yamaha");
function changearray(&$val, $key, $prefix)
{
$val = "$prefix: $val";
}
function printarray($itemvalue, $itemkey)
{
echo "$itemkey : $itemvalue<br>";
}
echo "before ...<BR>";
array_walk($cars, 'printarray');
array_walk($cars, 'changearray', 'car');
echo "after...<BR>";
array_walk($cars, 'printarray');
?>

The array_walk_recursive() Function


The array_walk_recursive does the same work done by array_walk... with the following
improvement: The array_walk_recursive goes over all elements of all arrays that are held as
elements of the main array.
<?php
$japan_cars = array("T" => "Toyota", "M" => "Mazda", "S" => "Suzuki", "Y"
=> "Yamaha");
$usa_cars = array("C" => "Chevrolet", "P" => "Pontiac", "C" =>
"Cryzler");
$cars = array("US" => $usa_cars, "JP" => $japan_cars);
function changearray(&$val, $key, $prefix)
{
$val = "$prefix: $val";
}
function printarray($itemvalue, $itemkey)
{
echo "$itemkey : $itemvalue<br>";
}
echo "before ...<BR>";
array_walk_recursive($cars, 'printarray');
array_walk_recursive($cars, 'changearray', 'car');
echo "after...<BR>";
array_walk_recursive($cars, 'printarray');
?>

Arrays Sorting
PHP core functions include various methods for sorting arrays.

The simplest ones are:

sort (array &$vec [, int $sort_flags ])

asort (array &$vec [, int $sort_flags ])

Calling sort() destroys all keys and reassign new ones starting from zero. Calling asort() keeps
the keys unchanged.

<?php
$japan_cars =
array("T" => "Toyota", "M" => "Mazda", "S" => "Suzuki", "Y" => "Yamaha");
$usa_cars =
array("C" => "Chevrolet", "P" => "Pontiac", "C" => "Cryzler");
echo "<P>before ...<BR>";
var_dump($japan_cars);
echo "<BR>";
var_dump($usa_cars);
sort($japan_cars);
asort($usa_cars);
echo "<P>after...<BR>";
var_dump($japan_cars);
echo "<BR>";
var_dump($usa_cars);
?>

Both sort() and asort() allows passing a second optional parameter, that configures the
operation. This second optional parameter can be one of the following possibilities:

SOFT_REGULAR

This is the default. Sorting will be performed according to elements' values and

without introducing any change.

SORT_NUMERIC

Each element's value will be first converted into a numeric value. The sorting will

be according to these numeric values.

SORT_STRING

Sorting will be according to the elements' values converted into strings.

The rsort() function sorts an array in a reverse order.

The rsort() function removes all elements' keys and

assign new ones.

<?php
$vec = array(
"a"=>"foofoo",
"b"=>"gondola",
"c"=>"israel",
"h"=>"honduras",
"d"=>"greece");
var_dump($vec);
rsort($vec);
echo "<p>";
var_dump($vec);
?>

The ksort() and krsort() functions sort an array by its elements' keys.

The usort(array &$vec, callback $function) function sorts an array by its elements' values and
using a user defined comparison function.

<?php
class Student
{
private $id;
private $average;
private $name;
function __construct($idVal, $averageVal, $nameVal)
{
$this->id = $idVal;
$this->average = $averageVal;
$this->name = $nameVal;
}
public function getId()
{
return $this->id;
}
public function getAverage()
{
return $this->average;
}
public function getName()
{
return $this->name;
}
public function __toString()
{
return $this->getName () . " id=" . $this->getId () .
" average=" . $this->getAverage ();
}
}
$vec = [
new Student ( 123123, 98, "danidin" ),
new Student ( 523434, 88, "moshe" ),
new Student ( 456544, 92, "spiderman" ),
new Student ( 744565, 77, "superman" )
];
echo "<h2>before</h2>";
foreach ( $vec as $k => $v )
{
echo "<Br>$k => " . $v;
}
usort ( $vec, function ($a, $b)
{
echo "<br>comparing between ".$a->getName()." and ".$b->getName();
return $a->getId() - $b->getId();
} );
echo "<h2>after</h2>";
foreach ( $vec as $k => $v )
{
echo "<Br>$k => " . $v;
}
?>

<?php
function cmp($a, $b)
{
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
$vec = array(12,532,12,56322343,232,5,2,1,1,1,4, 2, 5, 6, 1);
usort($vec, "cmp");
foreach ($vec as $key => $value)
{
echo "$key: $value<BR>";
}
?>

<?php
function cmp($a, $b)
{
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
$vec = array(12,532,12,56322343,232,5,2,1,1,1,4, 2, 5, 6, 1);
usort($vec, "cmp");
foreach ($vec as $key => $value)
{
echo "$key: $value<BR>";
}
?>
Array Shuffle
Calling the shuffle() function will scramble arrays' elements in a randomize order.

Arrays Randomized Elements

Using the array_rand(array $input [, int $num_req ] ) function we can get randomized selected
elements from our array. The first parameter is our array. The second parameter is the number
of elements we request.

If we request one element only, array_rand() returns the key for the random element. If we
request more than one element, array_rand() returns an array of keys for the random elements.

<?php
$vec = array("a","b","c","d","f","g","h");
$random_keys = array_rand($vec,3);
echo $vec[$random_keys[0]];
echo "<BR>";
echo $vec[$random_keys[1]];
echo "<BR>";
echo $vec[$random_keys[2]];
echo "<BR>";
?>

Arrays as Stacks
The array_push() and array_pop() functions enable us to use an array as a stack.

int array_push ( array &$array , mixed $var [, mixed $... ] )

This function pushes the passed values onto the end of the array. The array's length is
increased by the number of the passed variables. This functions returns the number of
elements, the array has.

mixed array_pop ( array &$array )

This function returns the last value of the array and shorten its length by one.

Arrays as Sets
The array_intersect() function returns an array containing all the values of array1 that are
present in all other arrays. The keys are preserved.
array array_intersect ( array $array1 , array $array2

[, array $ ... ] )

<?php
$vecA = array("il"=>"israel","ru"=>"russia","fr"=>"france","jo"=>"jordan");
var_dump($vecA);
echo "<br/>";
$vecB = array("ill"=>"israel","ru"=>"russia","fr"=>"franc","jo"=>"jordan");
var_dump($vecB);
echo "<br/>";
$vecC = array_intersect($vecA,$vecB);
var_dump($vecC);
?>

Arrays Shorter Syntax


As of PHP 5.4 we can create new arrays in the following new short syntax:

$vec = [34,234,75,4];

<?php
$vec_a = [4,6,2,7];
$vec_b = ['a'=>'australia','b'=>'belgium','c'=>'canada'];
foreach($vec_a as $k=>$v)
{
echo " ".$k."=>".$v;
}
foreach($vec_b as $k=>$v)
{
echo " ".$k."=>".$v;
}

Array Dereferencing

As of PHP 5.5 it is possible to dereference the array directly.


<?php
echo ["david","anat","limor","ilana"][0];
?>
Result: david

As of PHP 5.5 we can develop a function that returns an array and use a call to that function as
if it was an array.

The ?? Operator
The ?? operator, that was introduced in PHP 7, is also known as the isset ternary operator, is a
shorthand notation for performing isset() checks in the ternary operator.

This new operator assists us with those cases in which we need to check whether the array we
work with has a specific key so we could use its value and if not, then another value will be used
instead.

$vec = ['a'=>'abba','b'=>'baba','m'=>'mama'];

//before PHP7

//$temp = isset($vec['d'])?$vec['d']:'default';

$temp = $vec['d']??'default';

echo "<h1>$temp</h1>";

Array Constants
PHP 5.6 added the possibility to define array constants using the const keyword. As of PHP 7
we can define array constants using the define() function.

<?php
define('IMAGE_TYPES', ['jpg', 'jpeg', 'png', 'gif']);
foreach(IMAGE_TYPES as $v) {
echo "<h2>".$v."</h2>";
}
echo "<h1>".IMAGE_TYPES[0]."</h1>";
?>
PHP FUNCTIONS
The real power of PHP comes from its functions.

PHP has more than 1000 built-in functions, and in addition you can create
your own custom functions.

PHP Built-in Functions


PHP has over 1000 built-in functions that can be called directly, from within a
script, to perform a specific task.

PHP User Defined Functions


Besides the built-in PHP functions, it is possible to create your own functions.

• A function is a block of statements that can be used repeatedly in a


program.
• A function will not execute automatically when a page loads.
• A function will be executed by a call to the function.

Create a User Defined Function in PHP


A user-defined function declaration starts with the word function:

Syntax
function functionName() {
code to be executed;
}
Note: A function name must start with a letter or an underscore. Function
names are NOT case-sensitive.

Tip: Give the function a name that reflects what the function does!

In the example below, we create a function named "writeMsg()". The opening


curly brace ( { ) indicates the beginning of the function code, and the closing
curly brace ( } ) indicates the end of the function. The function outputs "Hello
world!". To call the function, just write its name followed by brackets ():

Example
<?php
function writeMsg() {
echo "Hello world!";
}

writeMsg(); // call the function


?>

PHP Function Arguments


Information can be passed to functions through arguments. An argument is just
like a variable.

Arguments are specified after the function name, inside the parentheses. You
can add as many arguments as you want, just separate them with a comma.

The following example has a function with one argument ($fname). When the
familyName() function is called, we also pass along a name (e.g. Jani), and the
name is used inside the function, which outputs several different first names,
but an equal last name:

Example
<?php
function familyName($fname) {
echo "$fname Refsnes.<br>";
}

familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
?>

The following example has a function with two arguments ($fname and $year):
Example
<?php
function familyName($fname, $year) {
echo "$fname Refsnes. Born in $year <br>";
}

familyName("Hege", "1975");
familyName("Stale", "1978");
familyName("Kai Jim", "1983");
?>

PHP is a Loosely Typed Language


In the example above, notice that we did not have to tell PHP which data type
the variable is.

PHP automatically associates a data type to the variable, depending on its


value. Since the data types are not set in a strict sense, you can do things like
adding a string to an integer without causing an error.

In PHP 7, type declarations were added. This gives us an option to specify the
expected data type when declaring a function, and by adding
the strict declaration, it will throw a "Fatal Error" if the data type mismatches.

In the following example we try to send both a number and a string to the
function without using strict:

Example
<?php
function addNumbers(int $a, int $b) {
return $a + $b;
}
echo addNumbers(5, "5 days");
// since strict is NOT enabled "5 days" is changed to int(5), and it will
return 10
?>

To specify strict we need to set declare(strict_types=1);. This must be on the


very first line of the PHP file.

In the following example we try to send both a number and a string to the
function, but here we have added the strict declaration:
Example
<?php declare(strict_types=1); // strict requirement

function addNumbers(int $a, int $b) {


return $a + $b;
}
echo addNumbers(5, "5 days");
// since strict is enabled and "5 days" is not an integer, an error will
be thrown
?>
The strict declaration forces things to be used in the intended way.

PHP Default Argument Value


The following example shows how to use a default parameter. If we call the
function setHeight() without arguments it takes the default value as argument:

Example
<?php declare(strict_types=1); // strict requirement
function setHeight(int $minheight = 50) {
echo "The height is : $minheight <br>";
}

setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?>

PHP Functions - Returning values


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

Example
<?php declare(strict_types=1); // strict requirement
function sum(int $x, int $y) {
$z = $x + $y;
return $z;
}
echo "5 + 10 = " . sum(5, 10) . "<br>";
echo "7 + 13 = " . sum(7, 13) . "<br>";
echo "2 + 4 = " . sum(2, 4);
?>

PHP Return Type Declarations


PHP 7 also supports Type Declarations for the return statement. Like with the
type declaration for function arguments, by enabling the strict requirement, it
will throw a "Fatal Error" on a type mismatch.

To declare a type for the function return, add a colon ( : ) and the type right
before the opening curly ( { )bracket when declaring the function.

In the following example we specify the return type for the function:

Example
<?php declare(strict_types=1); // strict requirement
function addNumbers(float $a, float $b) : float {
return $a + $b;
}
echo addNumbers(1.2, 5.2);
?>

You can specify a different return type, than the argument types, but make sure
the return is the correct type:

Example
<?php declare(strict_types=1); // strict requirement
function addNumbers(float $a, float $b) : int {
return (int)($a + $b);
}
echo addNumbers(1.2, 5.2);
?>
PHP Functions
PHP functions are similar to other programming languages. A function is a piece of
code which takes one more input in the form of parameter and does some processing
and returns a value.
You already have seen many functions like fopen() and fread() etc. They are built-in
functions but PHP gives you option to create your own functions as well.
There are two parts which should be clear to you −

• Creating a PHP Function


• Calling a PHP Function
In fact you hardly need to create your own PHP function because there are already
more than 1000 of built-in library functions created for different area and you just need
to call them according to your requirement.
Please refer to PHP Function Reference for a complete set of useful functions.

Creating PHP Function


Its very easy to create your own PHP function. Suppose you want to create a PHP
function which will simply write a simple message on your browser when you will call it.
Following example creates a function called writeMessage() and then calls it just after
creating it.
Note that while creating a function its name should start with keyword function and all
the PHP code should be put inside { and } braces as shown in the following example
below −
<html>

<head>
<title>Writing PHP Function</title>
</head>

<body>

<?php
/* Defining a PHP Function */
function writeMessage() {
echo "You are really a nice person, Have a nice time!";
}

/* Calling a PHP Function */


writeMessage();
?>

</body>
</html>

This will display following result −


You are really a nice person, Have a nice time!

PHP Functions with Parameters


PHP gives you option to pass your parameters inside a function. You can pass as
many as parameters your like. These parameters work like variables inside your
function. Following example takes two integer parameters and add them together and
then print them.
<html>

<head>
<title>Writing PHP Function with Parameters</title>
</head>

<body>

<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}

addFunction(10, 20);
?>

</body>
</html>

This will display following result −


Sum of the two numbers is : 30

Passing Arguments by Reference


It is possible to pass arguments to functions by reference. This means that a reference
to the variable is manipulated by the function rather than a copy of the variable's value.
Any changes made to an argument in these cases will change the value of the original
variable. You can pass an argument by reference by adding an ampersand to the
variable name in either the function call or the function definition.
Following example depicts both the cases.
<html>

<head>
<title>Passing Argument by Reference</title>
</head>
<body>

<?php
function addFive($num) {
$num += 5;
}

function addSix(&$num) {
$num += 6;
}

$orignum = 10;
addFive( $orignum );

echo "Original Value is $orignum<br />";

addSix( $orignum );
echo "Original Value is $orignum<br />";
?>

</body>
</html>

This will display following result −


Original Value is 10
Original Value is 16

PHP Functions returning value


A function can return a value using the return statement in conjunction with a value or
object. return stops the execution of the function and sends the value back to the
calling code.
You can return more than one value from a function using return array(1,2,3,4).
Following example takes two integer parameters and add them together and then
returns their sum to the calling program. Note that return keyword is used to return a
value from a function.
<html>

<head>
<title>Writing PHP Function which returns value</title>
</head>

<body>

<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
return $sum;
}
$return_value = addFunction(10, 20);

echo "Returned value from the function : $return_value";


?>

</body>
</html>

This will display following result −


Returned value from the function : 30

Setting Default Values for Function Parameters


You can set a parameter to have a default value if the function's caller doesn't pass it.
Following function prints NULL in case use does not pass any value to this function.
<html>

<head>
<title>Writing PHP Function which returns value</title>
</head>

<body>

<?php
function printMe($param = NULL) {
print $param;
}

printMe("This is test");
printMe();
?>

</body>
</html>

This will produce following result −


This is test

Dynamic Function Calls


It is possible to assign function names as strings to variables and then treat these
variables exactly as you would the function name itself. Following example depicts this
behaviour.
<html>

<head>
<title>Dynamic Function Calls</title>
</head>

<body>

<?php
function sayHello() {
echo "Hello<br />";
}

$function_holder = "sayHello";
$function_holder();
?>

</body>
</html>

This will display following result −


Hello
Array

is used to aggregate a series of similar items together, arranging and dereferencing them in some specific way.

•Each member of the array index references a corresponding value and can be a simple numerical reference to the value’s position in the series, or it could have some direct correlation to the
value.

•PHP array does not need to declare how many elements that the array variable have.

•Array index in PHP can be also called as array keys.

•Array can be used as ordinary array same as in C and C++ arrays.

print_r() function

short for print recursive. This takes an argument of any type and prints it out, which includes printing all its parts recursively.

var_dump()function

is same as the print_rfunction except that it prints additional information about the size and type of the values it discovers

print_r() and var_dump() functions are commonly used for debugging. The point of this of these functions is to help you visualize what’s going on with compound data structures like arrays

foreach()function

is a statement used to iterate or loop through the element in an array. With each loop, a foreachstatement moves to the next element in an array.

foreachstatement

specify an array expression within a set of parenthesis following the foreachkeyword.


Syntax

Array: Looping through array elements

$arr The name of the array that you’re walking through.

$key The name of the variable where you want to store the key. (optional)

$value The name of the variable where you want to store the value

Examples
Arrays: Sorting

PHP User Defined Functions

Functions

is a group of PHP statements that performs a specific task. Functions are designed to allow you to reuse the same code in different locations.

User defined functions

functions that are provided by the user of the program.

Predefined functions

functions that are built-in into PHP to perform some standard operations

Syntax

functionname(param){

//code to be executed by the function

Where
function –is the keyword used to declare a function

name –is the name of the function or function identifier

param–is the formal parameters of the function. Parameter must follow the rule of naming identifier.

Example without parameter:


Example with parameter:

Example function that returns a value


Global Variables

is one that declared outside a function and is available to all parts of the program.

Local Variables

is declared inside a function and is only available within the function in which it is declared.

Static Variables

is used to retain the values calls to the same function.


Examples:

Output:

Output:
Output:
Output:

You might also like