0% found this document useful (0 votes)
5 views

Web Technology-1 Chp 3

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Web Technology-1 Chp 3

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

CHAPTER

3
Arrays
Objectives…
To understand Basic Concepts of Arrays
To study Types of Arrays in PHP
To learn Traversing Arrays and Extracting Data from Arrays

3.0 INTRODUCTION [April 16, 18]


• An array is a collection of data values, organized as an ordered collection of key-value
pairs.
• PHP arrays stores multiple values of different data type in a single variable at a time.
• Commonly used terms or element in array are explained below:
1. Element: Element of an array is the items it contains. An array can contain one or
more elements.
2. Value: Each element contains one value.
3. Key or index: Key or index of an array is a unique number or a string that is
associated with each value of an element.
4. Length: The length of an array is the number of elements it contains.
First index Element
(at index 8)

0 1 2 3 4 5 6 7 8 9 Indices

Array length is 10
Fig. 3.1: Element of Array
Creating an Array:
• In PHP, an array can be created using the array() language construct. It takes any
number of comma-separated key => value pairs as arguments.
Syntax:
$array_name = array
{
key1 => value1,
key2 => value2,
key3 => value3,
...
};
3.1
Web Technologies - I Arrays

• The key can either be an integer or a string. The value can be of any type.
For example:
<?php(
$month = array
0 => "January";
1 => "February";
);
?>

3.1 INDEXED VS ASSOCIATIVE ARRAYS [April 18]

• There are two types of arrays in PHP namely, Indexed array (with a numeric index)
and Associative array (with named keys).

3.1.1 Indexed Array [April 18]

• The keys of an indexed array are integers beginning at 0. Indexed arrays are used
when identification of array elements are by their position.
For example:
$city = array( 0 => “Pune”, 1 => “Mumbai”, 2 => “Delhi”);
echo $city[1]; // Mumbai
• Indexed array can also be created without keys. In this case the key will be started
from 0.
For example:
$city = array(“Pune”, “Mumbai”, “Delhi”);
echo $city[3]; // Chennai

3.1.2 Associative Array [April 16, 18, 19, Oct. 17]

• An associative array has strings as keys. Associative array will have their index as
string so that we can establish a strong association between key and values.
For example:
$marks = array(“Maths” => 36, “Physics” => 28, “Chemistry” => 30);
echo $marks[‘Physics’]; // 28
$v = array(“a” => “one”, “b” => “two”, “c” => “three”);
echo $v[‘a’]; // one
• PHP internally stores all arrays as associative arrays, so the only difference between
associative and indexed arrays is what the keys happen to be.
• In both cases, the keys are unique i.e., we can’t have two elements with the same key,
regardless of whether the key is a string or an integer.
3.2
Web Technologies - I Arrays

3.2 IDENTIFYING ELEMENTS OF AN ARRAY


• We can access specific values from an array using array variable’s name followed by
element’s keys (i.e. index) within square brackets.
$A[‘one’]
$A[1]
• The key can be either a string or an integer. String values that are equivalent to
integer numbers (without leading zeros) are treated as integers i.e. A[1] and A[‘1’]
reference the same element. But A[‘01’] references a different element.
• Negative numbers are valid keys. No need to quote single word strings i.e. $A[‘one’]
and $A[one] both are same.
• But for better PHP style, always use quotes, because quote less keys are
indistinguishable from constants.
For example:
define (‘index’, 5);
echo $array [index];
• Echo statement will consider array[5] instead of array[‘index’]. If we interpolate the
array variable, quotes (‘… ’ or “… ”) must not be used.
For example:
echo “Hello $person[‘name’]”; // Syntax Error
echo “Hello $person[“name”]”; // Syntax Error
echo “Hello $person[name]”; // ok
Modifying Values of an Array:
• To change an existing value of an element, we need to specify the new value in the
array mentioning the key of that element in [] brackets.
Syntax:
$array_name[existing_key] = “new_value”;
For example:
<?php
$month = array(
0 => “January”,
1 => “February”,
2 => “March”,
)
array[2] = “December”;
?>
3.3
Web Technologies - I Arrays

• To remove a key/value pair, call the unset() function on it.


<?php
$arr = array(5 => 1, 12 => 2);
unset($arr[5]); // This removes the element from the array by key
unset($arr); // This deletes the whole array
?>

3.3 STORING DATA IN ARRAYS


• Storing a value in an array will create the array if it didn’t already exist. Use simple
assignment to initialize an array in the program.
For indexed array:
$a[0]=10;
$a[1]=20;
$a[2]=30;
For associative array:
$a[‘one’]=1;
$a[‘two’]=2;
$a[‘three’]=3;
• Another method to initialize an array is use the array() construct, which builds an
array from its arguments.
For example:
$a=array(1, 2, 3);
• This builds an indexed array and index values (starting from 0) are created
automatically.
For example:
$a=array(‘one’ ⇒ 1, ‘two’ ⇒ 2, ‘three’ ⇒ 3);
• This structure creates an associative array.
For example:
$a=array();
Here, it constructs empty array.
• It is possible to specify the key only for some elements and leave it out for others:
For example:
$v = array(“a”, “b”, 6 ⇒ “c”, “d”, “e”);
Here, v[0] = "a", v[1] = "b",
v[6] = "c", v[7] = "d",
v[8] = "e"

3.4
Web Technologies - I Arrays

For example:
$a = array(‘one’ ⇒ 1, 2, 3);
then a[‘one’]=1
a[0]=2
a[1]=3
3.3.1 Adding Values to the End of Array [April 17]
• To insert more values at the end of existing array, use [ ] syntax.
For example: Indexed array:
$A=array(1, 2, 3);
$A[ ]=4; // $A[3]=4
For example: Associative array:
$A=array(‘one’ ⇒ 1, ‘two’ ⇒ 2, ‘three’ ⇒ 3);
$A[ ]=4; // $A[0]=4
3.3.2 Assigning a Range of Values
• The range() function creates an array of consecutive integer or character between two
values we pass to it as a parameter.
Syntax: array range(mixed $start, mixed $end [, number $step = 1])
• Returns an array of elements from start to end, inclusive. Step is an optional argument
which indicates the difference between each consecutive element of an array.
$number = range(2, 5); // $number = array(2, 3, 4, 5);
$letter = range(‘a’, ‘d’); // $ letter = array( (‘a’, ‘b’, ‘c’, ‘d’)
$a = range(5, 2); // $a = array( (5, 4, 3, 2)
• Only the first character of the string argument is used to build the range.
range(‘aaa’, ‘zzz’) // same as range (‘a’, ‘z’)
For example:
<?php
$number = range(0,50,10);
$character=range('a','i',2)'
print_r ($number);
print_r ($ characters);
?>
Output:
Array ( [0] => 0 [1] => 10 [2] => 20 [3] => 30 [4] => 40 [5] => 50 )

3.3.3 Getting the Size of an Array [April 17, 19]


• The count() functions are used to return the number of elements in the array.
Syntax: count($array, $mode);
For example:
$a = array(1, 2, 3, 4);
$size = count($a); // size is 5
3.5
Web Technologies - I Arrays

• The sizeof() function is an alias of the count() function.


Syntax: sizeof($array, $mode);
For example:
$a = array(100 => ‘one’, 200 => ‘two’, 300 => ‘three’);
$size = sizeof($a); // size is 3
3.3.4 Padding an Array
• For padding an array array_pad() function is used. This function pads array to the
specified length with a value.
Syntax: array array_pad (array $array, int $size, mixed $value)
Where, array_pad() returns a copy of the ‘array’ padded to size specified by ‘size’ with
value ‘value’. If ‘size’ is positive then the array is padded on the right, if it's negative
then it is padded on the left.
$a = array(1, 2, 3);
$pad = array_pad($a, 5, 0);
// $pad is now array (1, 2, 3, 0, 0)
$pad = array_pad($a, −5, 0);
// $pad is now array (0, 0, 1, 2, 3)
• If we pad an associative array, existing keys will be preserved. New elements will have
numeric keys starting with 0.
For example:
<?php
$arr = array("a"=>"Horse","b"=>"Cat","c"=>"Dog");
print_r(array_pad($arr,7, "COW"));
?>
Output:
Array
{
[a] => Horse
[b] => Cat
[c] => Dog
[0] => COW
[1] => COW
[2] => COW
[3] => COW
}
3.6
Web Technologies - I Arrays

3.4 MULTIDIMENSIONAL ARRAY [April 16]


• PHP also support multi-dimensional array. In 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.
• A two-dimensional array is an array of arrays. A three-dimensional array is an array
of arrays of arrays.
• The values in the multi-dimensional array are accessed using multiple index.
$row0=array(1, 2, 3);
$row1=array(4, 5, 6);
$row2=array(7, 8, 9);
$multi=array($row0, $row1, $row2);
nd th
$val=$multi[2][0]; // 2 row, 0 column and $val=7
For example:
<?php
$marks = array(
"Amar" => array (
"physics" => 35,
"maths" => 30,
"chemistry" => 39
),
"Kiran" => array (
"physics" => 30,
"maths" => 32,
"chemistry" => 29
),
"Deepa" => array (
"physics" => 31,
"maths" => 22,
"chemistry" => 39
)
);
/* Accessing multi-dimensional array values */
echo "Marks for Amar in physics : " ;
echo $marks['Amar']['physics'] . "<br />";
echo "Marks for Kiran in maths : ";
echo $marks['Kiran']['maths'] . "<br />";
echo "Marks for Deepa in chemistry : " ;
echo $marks['Deepa']['chemistry'] . "<br />";
?>

3.7
Web Technologies - I Arrays

Output:
Marks for Amar in physics: 35
Marks for Kiran in maths: 32
Marks for Deepa in chemistry: 39

3.5 EXTRACTING MULTIPLE VALUES


• To copy an array’s values into variables use the list() construct or function.
Syntax: list($var1, $var2, …)=$array;
First value of an array is copied into var1, second value into var2 and so on.
For example:
$a=array(1, 2, 3);
list($x, $y, $z)= $a; // $x=1, $y=2, $z=3
• If array has more values than listed variables, then extra values are ignored.
For example:
$a=array(1, 2, 3);
list($x, $y)= $a; // $x=1, $y=2
• If list has more variables than in array the extra values are set to NULL.
For example:
$a=array(1, 2, 3);
list($x, $y, $z, $m)= $a; // $x=1, $y=2, $z=3; $m=NULL
• Two or more consecutive commas in the list() skip the values in array.
For example:
$A=(1, 2, 3, 4, 5)
list($x,, $y,, $z)= $A; // $x=1, $y=3, $z=5
<?php
$my_array = array("mango", "apple", "orange");
list($a, $b, $c) = $my_array;
echo "I have several fruits, $a, $b and $c.";
?>
Output:
I have several fruits, mango, apple and orange
• The list() function only works on numerical arrays and assumes the numerical indices
start at 0.
3.5.1 Slicing an Array [April 18]
• To extract a slice of the array, use the array_slice() function.
Syntax: array array_slice(array $array, int $offset
[, int $length = NULL [, bool $preserve_keys = false ]])

3.8
Web Technologies - I Arrays

• First parameter ‘array’ is the input array. If offset is non-negative, the slicing will start
at this point. If offset is negative, the slicing will start that far from the end of the
‘array’.
For example:
$input = array("a", "b", "c", "d", "e");
$output = array_slice($input, 2); // returns "c", "d", and "e"
• If the parameter ‘length’ is given and is positive, then the slicing will have up to that
many elements in it. If the array is shorter than the ‘length’, then only the available
array elements will be present.
• If ‘length’ is given and is negative then the sequence will stop that many elements
from the end of the array. If it is omitted, then the sequence will have everything from
‘offset’ up until the end of the ‘array’.
$input = array("a", "b", "c", "d", "e");
$output = array_slice($input, 0, 3); // returns "a", "b", and "c"
$output = array_slice($input, -2, 1); // returns "d"
• The array_slice() will reorder and reset the numeric array indices by default. You can
change this behavior by setting ‘preserve_keys’ to True.
For example:
<?php
$input = array("a", "b", "c", "d", "e");
// note the differences in the array keys
print_r(array_slice($input, 2, 2));
print_r(array_slice($input, 2, 2, true));
?>
Output:
Array{
[0] => c
[1] => d
}
Array
{
[2] => c
[3] => d
}

3.5.2 Splitting an Array into Chunks


• To divide an array into smaller, evenly sized arrays, use the array_chunk( ) function.
Syntax:
array array_chunk (array $input, int $size [, bool $preserve_keys]);

3.9
Web Technologies - I Arrays

• This function returns a multidimensional numerically indexed array, starting with


zero, with each dimension containing size elements.
• The parameter_keys is optional. If not set it takes the default value FALSE which will
reindex the chunk numerically.
For example:
<?php
$input_array = array('a', 'b', 'c', 'd', 'e');
print_r(array_chunk($input_array, 2));
?>
Output:
Array
{
[0] => Array
{
[0] => a
[1] => b
}
[1] => Array
{
[0] => c
[1] => d
}
[2] => Array
{
[0] => e
}
}
• When the parameter preserve_keys is set to TRUE, keys will be preserved.
For example:
<?php
$input_array = array('a', 'b', 'c', 'd', 'e');
print_r(array_chunk($input_array, 2, true));
?>
Output:
Array
{
[0] => Array
{
[0] => a
[1] => b
}

3.10
Web Technologies - I Arrays

[1] => Array


{
[2] => c
[3] => d
}
[2] => Array
{
[4] => e
}
}

3.5.3 Keys and Values [Oct. 18]

• The array_keys() function returns an array consisting of only the keys in the array.
Syntax:
array array_keys (array $input [, mixed $search_value [, bool
$strict = false]]);
• First parameter is an array containing keys to return. Second and third parameters
are optional.
For example:
<?php
$array = array(0 => 100, "color" => "red");
print_r(array_keys($array));
array = array("color" => array("blue", "red", "green"),
"size" => array("small", "medium", "large"));
print_r(array_keys($array));
?>
Output:
Array
{
[0] => 0
[1] => color
}
Array
{
[0] => color
[1] => size
}
3.11
Web Technologies - I Arrays

• In the above program only keys are returned by the array_keys function from both the
arrays.
• If search_value is specified then that value will be searched and keys of that value will
be returned.
For example:
<?php
$array = array("blue", "red", "green", "blue", "blue");
print_r(array_keys($array, "blue"));
?>
Output:
Array
{
[0] => 0
[1] => 3
[2] => 4
}
• The parameter ‘strict’ determines if strict comparison (===) should be used during the
search.
3.5.4 Checking whether an Element Exists
• The array_key_exists() function is used to see if an element exists in the array.
Syntax: bool array_key_exists (mixed $key, array $array)
• This function returns TRUE if the given key is set in the array otherwise False.
For example:
<?php
$a=array(‘one’ ⇒ 1, ‘two’ ⇒ 2);
if(array_key_exists(‘one’, $a))
{
echo “Key ‘one’ exists in the array”;
}
else
{
echo "Key ‘one’ does not exist in the array";
}
?>
Output:
Key ‘one’ exists in the array
3.12
Web Technologies - I Arrays

3.5.5 Removing and Inserting Elements in an Array [Oct. 17]


• The array_splice() function can remove or insert elements in an array.
• The function removes selected elements from an array and replaces it with new
elements. The function also returns an array with the removed elements.
Syntax:
array array_splice (array &$input, int $offset [, int $length
[, mixed $replacement = array()]]);
• This function removes the elements designated by offset and length from
the input array, and replaces them with the elements of the replacement array, if
supplied. It returns an array containing the extracted elements.
For example:
$subjects = array('physics', 'chem', 'math', 'bio', 'cs', 'drama');
$removed = array_splice($subjects, 2);
// $removed is array('math', 'bio', 'cs', 'drama')
// $subjects is array('physics', 'chem')
Here ‘length’ is not specified and offset is 2 hence the function removes everything
from position 2 to the end of the array subjects. The function returns the removed
elements. After removing the array subjects will be reduced.
• The example below removes only 3 elements i.e. 'math', 'bio', 'cs':
$subjects = array('physics', 'chem', 'math', 'bio', 'cs', 'drama');
$removed = array_splice($subjects, 2, 3);
// $removed is array('math', 'bio', 'cs')
// $subjects is array('physics', 'chem', 'drama')
• To insert new elements use the fourth argument
$subjects = array('physics', 'chem', 'math', 'bio', 'cs', 'drama');
$new = array('law', 'business');
$removed = array_splice($subjects, 2, 3, $new);
// $removed is array('math', 'bio', 'cs')
// $subjects is array('physics', 'chem', 'law', 'business', 'drama')
• The size of the replacement array doesn’t have to be the same as the number of
elements you delete. The array grows or shrinks as needed.
• The array_splice() also works on associative arrays.
<?php
a1=array("0"=>"red","1"=>"green");
$a2=array("a"=>"purple","b"=>"orange");
array_splice($a1,1,0,$a2);
print_r($a1);
?>
Output:
Array ([0] => red [1] => purple [2] => orange [3] => green)
rd
• Since 3 parameter is 0 so nothing will be removed, and array $a2 will get inserted
from index 1. Here, new keys will be assigned starting with 0.
3.13
Web Technologies - I Arrays

3.6 CONVERTING BETWEEN ARRAYS AND VARIABLES


• PHP provides two functions extract() and compact(), that convert between arrays and
variables. [April 17]
1. extract() Function: [Oct. 17]
• The extract() function automatically creates local variables from an array. The indexes
of the array elements are the variable names:
Syntax: int extract(array &$array)
• This function is used to import variables from an array into the current symbol table.
It takes an associative ‘array’ and treats keys as variable names and values as variable
values.
• For each key/value pair it will create a variable in the current symbol table, subject to
extract type and prefix parameters.
• The function returns the number of variables successfully imported into the symbol
table.
For example:
<?php
$n = array("a"=>10, "b"=>35, "c"=>12);
extract($n);
echo $a. " " . $b. " " . $c;
?>
Output:
10 35 12
2. compact() Function:
• The compact() function creates an array from variables and their values.
Syntax: array compact(mixed $varname1 [, mixed $... ])
• This function is the complement of extract( ). It takes variable names as parameters
and creates an associative array whose keys are the variable names and whose values
are the variable’s values.
• Returns the output array with all the variables added to it.
For example:
<?php
$n1 = 10;
$n2 = 20;
$n3 = 30;
$arr = array("n1", "n2", "n3");
$output = compact($arr);
print_r($output);
?>
Output:
Array ([n1] => 10 [n2] => 20 [n3] => 30)
3.14
Web Technologies - I Arrays

3.7 TRAVERSING ARRAYS


• Traversing an array means to visit each and every element of array using a looping
structure and iterator functions.
• There are several ways to traverse arrays in PHP. Some of them are given below:
Using foreach Construct:
• PHP provides a very special kind of looping statement called foreach that allows you to
loop over arrays. The foreach statement only works with arrays and objects.
For example:
$a = array(‘aaa’, ‘bbb’, ‘ccc’);
foreach($a as $value)
{
echo “$value\n”;
}
Output:
aaa
bbb
ccc
• In the above foreach loop, the loop will be executed once for each element of $a, i.e. 3
times. And for each iteration $value will store the current element.
For example:
$a=array(‘one’ ⇒ 1, ‘two’ ⇒ 2, ‘three’ ⇒ 3);
foreach ($A as $k ⇒ $v)
{
echo “$k is $v \n”;
}
Output:
one is 1
two is 2
three is 3
• In this case the key for each element is stored in $k and the corresponding value is
stored in $v.
• The foreach operates on copy of array, not on array itself.
Using a for Loop:
• The for loop operates on the array itself, not on a copy of the array.
3.15
Web Technologies - I Arrays

For example:
$a = array(1, 2, 3, 4);
for($i=0; $i<count($a); $i++)
{
echo $A[i] . “<br>”;
}
Output:
1
2
3
4
Using Iterator Functions:
• Every PHP array keeps track of the current element. The pointer to the current
element is known as the iterator. PHP has functions to set, move, reset this iterator.
• The iterator functions are:
1. current(): Returns the currently pointed element.
2. reset(): Moves the iterator to the first element in the array and returns it.
3. next(): Moves the iterator to the next element in the array and returns it.
4. prev(): Moves the iterator to the previous element in the array and returns it.
5. end(): Moves the iterator to the last element in the array and returns it.
6. each(): Returns the key and value of the current element as an array and moves
the iterator to the next element in the array.
7. key(): Returns the key of the current element.
For example:
<?php
$transport = array('foot', 'bike', 'car', 'plane');
$mode = current($transport); // $mode = 'foot';
$mode = next($transport); // $mode = 'bike';
$mode = current($transport); // $mode = 'bike';
$mode = prev($transport); // $mode = 'foot';
$mode = end($transport); // $mode = 'plane';
$mode = current($transport); // $mode = 'plane';
?>
3.16
Web Technologies - I Arrays

• After executing each() the iterator moves to the next element.


<?php
$a = array(10, 20, 30, 40, 50);
reset($a);
while (list($key, $val) = each($a))
{
echo "$key => $val <br>";
}
?>
Output:
0 => 10
1 => 20
2 => 30
3 => 40
4 => 50
Calling a Function for Each Array Element:
• The array_walk() function apply a user defined function to each element of an array.
Syntax: bool array_walk (array &$arr, callable $function_name)
• This function takes two parameters, first is the input array and second is the user
defined function name.
• The user defined function takes two arguments, first contains arr’s value and second
contains arr’s key.
• Returns True on success or False on failure.
For example:
<?php
function print_row($v, $k)
{
echo "$v $k <br>";
}
$a = array(10, 20, 30, 40);
array_walk($a, 'print_row');
?>
Output:
10 0
20 1
30 2
40 3
3.17
Web Technologies - I Arrays

• In the above program the ‘print_row’ function will be called 4 times i.e. for each
elements of the array $a. The ‘print_row’ function then displays the values along with
the keys.
Reducing an Array:
• The array_reduce() function apply a user defined function to each element of an array,
so as to reduce the array to a single value.
Syntax: mixed array_reduce(array $array, callable $callback
[, mixed $initial = NULL])
• The function takes two arguments: the running total, and the current value being
processed. It should return the new running total.
For example:
<?php
function add($sum, $value)
{
$sum += $value;
return $sum;
}
$n = array(2, 3, 5, 7);
$total = array_reduce($n, 'add');
echo $total;
?>
Output:
17
• The function ‘add’ will be called for each element, i.e. 4 times. The function then finds
the sum and returns it.
• If the optional initial is available, it will be used at the beginning of the process.
$total = array_reduce($n, 'add', 10);
cho $total; // 27 (i.e. 10 + 17)
Searching for Values:
• The in_array() function searches if a value exists in an array or not.
Syntax:
bool in_array(mixed $to_find, array $input [, bool $strict = FALSE])
• The in_array() function returns true or false, depending on whether the element
‘to_find’ is in the array ‘input’ or not.
3.18
Web Technologies - I Arrays

For example:
<?php
$os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os))
{
echo "Got Irix";
}
if(in_array("mac", $os))
{
echo "Got mac";
}
?>
• The second condition is false because in_array() is case-sensitive, so the program
above will display:
Got Irix
• If the third parameter strict is set to TRUE then the in_array() function will also check
the types of the $value.
For example:
<?php
$a = array(2, 3, "4", "5");
if(in_array('3', $a, true))
{
echo "'3' found with strict check\n";
}
if(in_array('4', $a, true))
{
echo "'4' found with strict check\n";
}
?>
Output:
'4' found with strict check
• In the above program the type of ‘3’ which we are searching is string but in the array
‘a’, 3 is integer. Hence first condition is false.
array_search() Function:
• The array_search() function search an array for a value and returns the key.
Syntax:
mixed array_search (mixed $ to_find, array $input [, bool $strict = FALSE])

3.19
Web Technologies - I Arrays

• The in_array() function returns the key of the element ‘to_find’ if it is found in the
array ‘input’, otherwise returns FALSE.
For example:
<?php
$a=array("a"=>"5","b"=>5,"c"=>"5");
echo array_search(5,$a,true);
?>
Output:
b

3.8 SORTING [April 16]


• The functions provided by PHP to sort an array are shown in following table:
sort() Ascending
sort indexed array by values reassign
rsort() Descending
indexes starting with 0.
usort() user_defined order
asort() ascending
sort array
arsort() descending
by values.
uasort() user_defined order
ksort() ascending
sort array
krsort() descending
by keys.
uksort() user_defined order
• Let us see above functions in detail.
1. sort() Function:
• This function sorts an indexed array in ascending order. This function assigns new
keys for the elements in array.
Syntax: bool sort(array &$array [, int $sort_flags = SORT_REGULAR])
For example:
<?php
$fruits = array("lemon", "orange", "banana", "apple");
sort($fruits);
print_r($fruits);
?>
Output:
Array ( [0] => apple [1] => banana [2] => lemon [3] => orange )
3.20
Web Technologies - I Arrays

• The optional second parameter sort_flags may be used to modify the sorting behavior
using these values:
(i) SORT_REGULAR: Compare items normally (don't change types)
(ii) SORT_NUMERIC: Compare items numerically
(iii) SORT_STRING: Compare items as strings
(iv) SORT_NATURAL: Compare items as strings using "natural ordering" like natsort()
2. rsort() Function:
• The syntax of rsort() function is same but it sorts an indexed array in descending
order.
3. usort() Function:
• The usort() function sorts an array using a user-defined comparison function.
Syntax: bool usort(array &$array, callable $value_compare_func)
• The ‘value_compare_func’ is a user defined function where, the first argument is
considered to be less than, equal to, or greater than the second, then the function
return an integer less than, equal to, or greater than zero respectively.
For example:
int callback (mixed $a, mixed $b)
<?php
function my_sort($a,$b)
{
if ($a==$b) return 0;
return ($a<$b)?-1:1;
}
$a=array(4,2,8,6);
usort($a,"my_sort");
print_r($a); // Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 )
?>
4. asort() Function: [Oct. 16, 17, 18]
• This function mainly used to sort associative array.
• The function maintains their key/value association after sorting the array elements.
For example:
<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana",
"c" => "apple");
asort($fruits);
print_r($fruits);
?>
Output::
Array ( [c] => apple [b] => banana [d] => lemon [a] => orange )
3.21
Web Technologies - I Arrays

5. ksort() Function: [April 18]


• This function sorts an array by key, maintaining key to data correlations. This is useful
mainly for associative arrays.
For example:
<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana",
"c" => "apple");
ksort($fruits);
print_r($fruits);
?>
Output:
Array ( [a] => orange [b] => banana [c] => apple [d] => lemon )

3.8.1 Natural Order Sorting


• PHP’s built-in sort functions correctly sort strings and numbers, but they don’t
correctly sort strings that contain numbers.
• For example: a1.php, a10.php, a5.php are three files. The normal order sorting
function will sort in this order, a1.php a10.php a5.php.
• For correct sort, we use natsort( ) and natcasesort( ) functions.
• The natsort() function sorts an array by using a "natural order" algorithm. The values
keep their original keys.
Syntax: bool natsort(array &$input)
For example:
<?php
$array1 = $array2 = array("img12.png", "img10.png", "img2.png",
"img1.png");
echo "Standard sorting<br>";
sort($array1);
print_r($array1);
echo "<br>Natural order sorting<br>";
natsort($array2);
print_r($array2);
?>
Output:
Standard sorting
Array ([0]=>img1.png [1]=>img10.png [2]=>img12.png [3]=>img2.png)
Natural order sorting
Array ([3]=>img1.png [2]=>img2.png [1]=>img10.png [0]=>img12.png)
3.22
Web Technologies - I Arrays

3.8.2 Sorting Multiple Arrays at Once


• The array_multisort() function sorts multiple arrays. The function takes a series of
arrays and sorting orders (SORT_ASC, SORT_DESC) as a parameter and sort several
arrays at once.
Syntax: array_multisort(array1 [, array2, ... ]);
For example:
<?php
$ar1 = array(10, 100, 100, 0);
$ar2 = array(1, 3, 2, 4);
array_multisort($ar1, $ar2);
var_dump($ar1);
var_dump($ar2);
?>
Output:
array(4)
{
[0]=> int(0)
[1]=> int(10)
[2]=> int(100)
[3]=> int(100)
}
array(4)
{
[0]=> int(4)
[1]=> int(1)
[2]=> int(2)
[3]=> int(3)
}
• In this example, after sorting, the first array will contain 0, 10, 100, 100. The second
array will contain 4, 1, 2, 3.
• The entries in the second array corresponding to the identical entries in the first array
(100 and 100) were sorted as well.
3.8.3 Reversing Arrays
• We can reverse array elements. The PHP array_reverse() function to reverse the order
of the array elements. It returns an array with items in reverse order.
1. array_reverse() Function:
• The array_reverse() function returns an array with elements in reverse order.
Syntax:
array array_reverse(array $input [, bool $preserve_keys = false])
3.23
Web Technologies - I Arrays

• If ‘preserve_keys’ is set to True then numeric keys are preserved.


For example:
<?php
$input = array('a', 'b', 'c', 'd');
$reversed = array_reverse($input);
$preserved = array_reverse($input, true);
print_r($input); // Array ( [0] => a [1] => b [2] => c [3] => d )
print_r($reversed);//Array ( [0] => d [1] => c [2] => b [3] => a )
print_r($preserved);// Array ( [3] => d [2] => c [1] => b [0] => a)
?>
2. array_flip() Function: [Oct. 18]
• The array_flip() function flips/exchanges all keys with their associated values in an
array.
Syntax: array array_flip(array $input)
For example:
<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue");
$result=array_flip($a1);
print_r($result);
?>
Output:
Array ([red] => a [green] => b [blue] => c)
3. shuffle() Function: [Oct. 16]
• The shuffle() function is used to traverse the elements in an array in an random order.
After shuffling the function assigns new keys to the elements
Syntax: shuffle($array);
For example:
<?php
$input = array('a', 'b', 'c', 'd');
shuffle($input);
print_r($input);
?>
Output:
Array ( [0] => c [1] => d [2] => b [3] => a )

3.9 ACTION OR ACTING ON ENTIRE ARRAY


• PHP has several useful functions for modifying or applying an operation to all
elements of an array.
3.24
Web Technologies - I Arrays

• We can merge arrays, find the difference, calculate the total, and more, all using built-
in functions.
1. array_sum() Function:
• The array_sum() function returns the sum of all the values in the array.
Syntax: array_sum($array);
For example:
<?php
$a = array(2, 4, 6, 8);
echo "sum(a) = " . array_sum($a) . "<br>";
$b = array("a" => 1.2, "b" => 2.3, "c" => 3.4);
echo "sum(b) = " . array_sum($b) . "<br>";
?>
Output:
sum(a) = 20
sum(b) = 6.9
2. array_merge() Function:
• Merges the elements of one or more arrays together so that the values of one are
appended to the end of the previous one.
Syntax:
array array_merge(array $array1 [, array $array2 [, array $array3...]])
• After merging the numeric keys are renumbered.
For example:
<?php
$a1=array("red","green");
$a2=array("blue","yellow");
print_r(array_merge($a1,$a2));
?>
Output:
Array ( [0] => red [1] => green [2] => blue [3] => yellow )
• If the input arrays have the same string keys, then the later value for that key will
overwrite the previous one.
• If however, the arrays contain numeric keys, the later value will not overwrite the
original value, but will be appended.
For example:
<?php
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid",4);
$result = array_merge($array1, $array2);
print_r($result);
?>
3.25
Web Technologies - I Arrays

Output:
Array
{
[color] => green
[0] => 2
[1] => 4
[2] => a
[3] => b
[shape] => trapezoid
[4] => 4
}
3. array_diff() Function:
• The array_diff() function identifies values from one array that are not present in
others.
Syntax:
array array_diff ( array $array1, array $array2 [, array $array3 ...] );
For example:
<?php
$a = array(1, 2, 3, 4);
$b = array(2, 4);
$result=array_diff($a,$b);
print_r($result);
?>
Output:
Array ( [0] => 1 [2] => 3 )
• From array $a the values 1 and 3 is not present in the array $b.
4. array_filter() Function: [April 18, Oct. 18]
• The array_filter() function filters the values of an array using a callback function.
• This function passes each value of the input array to the callback function. If the
callback function returns true, the current value from input is returned into the result
array. Array keys are preserved.
Syntax:
array array_filter ( array $input [, callback $callback] );
For example:
<?php
function is_odd($var)
{
return ($var % 2);
}
3.26
Web Technologies - I Arrays

$a = array(6, 7, 8, 9, 10, 11, 12);


$odd = array_filter($a, "is_odd");
echo "Odd Numbers:<br>";
print_r($odd);
?>
Output:
Odd Numbers:
Array ( [1] => 7 [3] => 9 [5] => 11 )
• In the above program array_filter function will call ‘is_odd’ function. Each element
will be passed one by one.
• For odd value the function will return 1 i.e. true. For true the array_filter function
returns the current value which will be stored in the array $odd.
PRACTICE QUESTIONS
Q.I Multiple Choice Questions:
1. Which function removes the first element from an array, and returns the value of
the removed element?
(a) array_unshift() (b) array_pop()
(c) array_shift() (d) array_push( )
2. Which function removes duplicate values from an array?
(a) array_del() (b) array_duplicate()
(c) array_remove() (d) array_unique()
3. Which of the following are not the iterator functions?
(a) reset( ) (b) each()
(c) key() (d) walk()
4. What is output of following PHP code:
$a = array(2, 3, "4", "5");
if (in_array('4', $a, true))
{
echo "'4' found \n";
}
else
echo"'4' Not found \n";
(a) '4' found (b) '4' Not found
(c) Warning (d) Both 2 and 3
5. Which function will merge the values together, forming a new array with the
preexisting key as its name?
(a) array_merge() (b) array_combine()
(c) array_merge_recursive() (d) array_merge_all()
3.27

You might also like