Web Technology-1 Chp 3
Web Technology-1 Chp 3
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
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";
);
?>
• There are two types of arrays in PHP namely, Indexed array (with a numeric index)
and Associative array (with named keys).
• 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
• 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.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.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.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.9
Web Technologies - I Arrays
3.10
Web Technologies - I Arrays
• 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
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
• 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
• 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
• 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