Download as pdf or txt
Download as pdf or txt
You are on page 1of 35

ARRAY FUNCTIONS

Prepared By: Mary Grace ventura


Array Manipulation Functions

print_r() rsort()
count() arsort()
sort() krsort()
asort() shuffle()
ksort() array_walk
print_r()
 useful function to print the contents of an array

<pre>
<?php
$a = array(‘a’ => ‘apple’,
‘b’ => ‘banana’,
‘c’ => array(‘x’,’y’,’z’));
print_r($a);
?>
</pre>
print_r()
 Sample Output:

Array
(
[a] => apple
[b] => banana
[c] => Array (
([0] => x
[1] => y
[2] => z
)
)
count()/sizeof()
 Returns the number of elements in an array

$a[0] = 1;
$a[1] = 3;
$a[2] = 5;
$result = count($a); //result ==3
$b[0] = 7;
$b[5] = 9;
$b[10] = 11;
$result= sizeof($b); //result == 3
sort()
 sorts an array but destroy the keys.
$<?php
$customers = array(
'Matthew' => 'matthew@gmail.com',
'Mark' =>'mark@yahoo.com',
'Luke’ =>'luke@hotmail.com');
sort($customers);
while (list($key,$val) = each ($customers)){
echo "Element $key equals $val<br />";
}
?>
Output Program of sort()

sorts the values,


but does not retain
the keys
Sorting Numbers
<?php
$data=array(15,81,14,100, 74,2);
//sort and print array
sort($data);
print_r($data);
?>
asort()
<?php
$customers = array(
'Matthew' => 'matthew@gmail.com',
'Mark' =>'mark@yahoo.com',
'Luke’ =>'luke@hotmail.com');
asort($customers);
while (list($key,$val) = each ($customers)){
echo "Element $key equals $val<br />";
}
?>

sorts the values,


and maintain
association w/ the
keys
asort()
<?php
//define array
$profile=array(
"fname" => "Susan",
"lname" => "Doe",
"sex" => "female",
"sector" => "Asset Management");
//sort by value
//output
//('sector' => 'Asset Management',
//'lname' => 'Doe',
//'sex' => 'female')
//'fname' => 'Susan',

asort($profile);
print_r($profile);
?>
ksort() function
<?php
$customers = array(
'Matthew' => 'matthew@gmail.com',
'Mark' =>'mark@yahoo.com',
'Luke’ =>'luke@hotmail.com');
ksort($customers);
while (list($key,$val) = each ($customers)){
echo "Element $key equals $val<br />";
}
?>

sorts the keys, and


maintain
association w/ the
values
Reverse Sorting
 rsort() – Sort an array in reverse order
 arsort() – Sort an array in reverse order and
maintain index association.
 krsort() – Sort an array by key in reverse order
shuffle()
 randomizes the order of elements in an array
 does not maintain association between keys and
values
$numbers = array(1=>1,2=>2,3=>3,4=>4);
shuffle($numbers);
print_r($numbers); //prints contents of array

 Sample Output:
Array
(
[0] => 2
[1] => 4
[2] => 3
[3] => 1
)
Randomizing and Reversing an Array

<?php
$rainbow=array('violet','indigo','blue','green',
'yellow','orange','red');
//randomize array
shuffle($rainbow);
print_r($rainbow);
echo "<br /><br />";
//reverse array
$arr=array_reverse($rainbow);
print_r($arr);
?>
Output of the Program

result of shuffle()

result of
array_reverse()
Searching Arrays
 The in_array function looks through an array for a
specified value and returns true if found.
<?php
$cities=array('London','Paris','Barcel
ona','Lisbon','Zurich');
//search array for value
echo in_array('Barcelona',$cities);
?>

result is : 1
Searching arrays using
array_key_exists()
<?php
$cities=array(
"United Kingdom" => "London",
"United States" => "Washington",
"France" => "Paris",
"India" => "Delhi");
//search array for key
echo
array_key_exists('India',$cities);
?>

result is : 1
Extracting Array Segments
 Extracts a segment of an array.
<?php
$rainbow=array('violet','indigo','blue'
,'green', 'yellow','orange','red');
//extract 3 central values
//output ('blue', 'green', 'yellow')
$arr= array_slice($rainbow,2,3);
print_r($arr);
?>

Output:
('blue', 'green', 'yellow')
Adding and Removing an Array
Element
$movies=array("The Lion King", "Cars","A Bug's Life");
//remove element from beginning of an array
array_shift($movies);

//remove element from end of an array


array_pop($movies);

//add element to end of an array


array_push($movies, 'Ratatouille');

//add element to beginning of an array


array_unshift($movies,'The Incredibles');

//print array

//output(The Incredibles, Cars, Ratatouille)


print_r($movies)
Adding and Removing Elements from
the Beginning of an Array
 The array_shift() function removes the first
element from the beginning of an array
 Passthe name of the array whose first element you
want to remove
 The array_unshift() function adds one or
more elements to the beginning of an array
 Passthe name of an array followed by comma-
separated values for each element you want to add

PHP Programming with MySQL, 2nd Edition 20


Adding and Removing Elements from the
Beginning of an Array (continued)
$TopSellers = array(
"Chevrolet Impala",
"Chevrolet Malibu",
"Chevrolet Silverado",
"Ford F-Series",
"Toyota Camry",
"Toyota Corolla",
"Nissan Altima",
"Honda Accord",
"Honda Civic",
"Dodge Ram");
array_shift($TopSellers);
array_unshift($TopSellers, "Honda CR-V");
echo "<pre>\n";
print_r($TopSellers);
echo "</pre>\n";

PHP Programming with MySQL, 2nd Edition 21


Adding and Removing Elements from the
Beginning of an Array (continued)

Figure 6-3 Output of an array modified with the array_shift()


and array_unshift() functions

PHP Programming with MySQL, 2nd Edition 22


Adding and Removing Elements from
the End of an Array
 The array_pop() function removes the last
element from the end of an array
 Passthe name of the array whose last
element you want to remove
 The array_push() function adds one or more
elements to the end of an array
 Passthe name of an array followed by
comma-separated values for each element
you want to add

PHP Programming with MySQL, 2nd Edition 23


Adding and Removing Elements from the End of
an Array (continued)
$HospitalDepts = array(
"Anesthesia",
"Molecular Biology",
"Neurology",
"Pediatrics");
array_pop($HospitalDepts);
array_push($HospitalDepts, "Psychiatry", "Pulmonary
Diseases");

PHP Programming with MySQL, 2nd Edition 24


Adding and Removing Elements Within
an Array
 The array_splice() function adds or removes
array elements
 The array_splice() function renumbers the
indexes in the array
 The syntax for the array_splice() function is:
array_splice(array_name, start,
characters_to_delete, values_to_insert);

PHP Programming with MySQL, 2nd Edition 25


Adding and Removing Elements Within
an Array (continued)
 To add an element within an array, include a value
of 0 as the third argument of the
array_splice() function

$HospitalDepts = array(
"Anesthesia", // first element (0)
"Molecular Biology", // second element (1)
"Neurology", // third element (2)
"Pediatrics"); // fourth element (3)
array_splice($HospitalDepts, 3, 0, "Ophthalmology");

PHP Programming with MySQL, 2nd Edition 26


Adding and Removing Elements Within
an Array (continued)
 To add more than one element within an array, pass
the array() construct as the fourth argument of the
array_splice() function
 Separate the new element values by commas
$HospitalDepts = array(
"Anesthesia", // first element (0)
"Molecular Biology", // second element (1)
"Neurology", // third element (2)
"Pediatrics"); // fourth element (3)
array_splice($HospitalDepts, 3, 0, array("Opthalmology",
"Otolaryngology"));

PHP Programming with MySQL, 2nd Edition 27


Adding and Removing Elements Within
an Array (continued)
 Delete array elements by omitting the fourth
argument from the array_splice() function
$HospitalDepts = array(
"Anesthesia", // first element (0)
"Molecular Biology", // second element (1)
"Neurology", // third element (2)
"Pediatrics"); // fourth element (3)
array_splice($HospitalDepts, 1, 2);

PHP Programming with MySQL, 2nd Edition 28


Adding and Removing Elements Within
an Array (continued)
 The unset() function removes array elements and
other variables
 Pass to the unset() function the array name and
index number of the element you want to remove
 To remove multiple elements, separate each index
name and element number with commas
unset($HospitalDepts[1], $HospitalDepts[2]);

PHP Programming with MySQL, 2nd Edition 29


Removing Duplicate Elements
 The array_unique() function removes duplicate
elements from an array
 Pass to the array_unique() function the name of
the array from which you want to remove duplicate
elements
 The array_values() and array_unique()
functions do not operate directly on an array
 The array_values() function returns an array
containing all the values of an array. Tip: The returned
array will have numeric keys, starting at 0 and increase
by 1.
 The array_unique() function does renumber the
indexes after removing duplicate values in an array

PHP Programming with MySQL, 2nd Edition 30


Removing Duplicate Array Elements

<?php
$duplicates=array('a','b','a','c','e','d','e'
);
//remove duplicates
//output:(a,b,c,e,d)
$uniques=array_unique($duplicates);
print_r($uniques);
?>
Removing Duplicate Elements
(continued)
$TopSellers = array(
"Ford F-Series", "Chevrolet Silverado", "Toyota Camry",
"Honda Accord", "Toyota Corolla", "Ford F-Series", "Honda
Civic",
"Honda CR-V", "Honda Accord", "Nissan Altima", "Toyota
Camry",
"Chevrolet Impala", "Dodge Ram", "Honda CR-V");
echo "<p>The 2008 top selling vehicles are:</p><p>";
$TopSellers = array_unique($TopSellers);
$TopSellers = array_values($TopSellers);
for ($i=0; $i<count($ TopSellers); ++$i) {
echo "{$TopSellers[$i]}<br />";
}
echo "</p>";

PHP Programming with MySQL, 2nd Edition 32


Removing Duplicate Elements
(continued)

Figure 6-4 Output of an array after removing duplicate values


with the array_unique() function

PHP Programming with MySQL, 2nd Edition 33


explode()
• Splits a string into array elements
<?php
$str= 'tinker, tailor, soldier, spy';
//convert string to array
//output: ('tinker', 'tailor',
'soldier','spy')
$arr = explode(',',$str);
print_r($arr);
?> Array ( [0] => tinker [1] => tailor [2]
=> soldier [3] => spy )
implode()
•Joins array elements into a string
<?php
$arr = array('one','two','three');
//convert array to string
//output: 'one and two and three'
$str = implode(' and ',$arr);
echo($str);
?>
one and two and three

You might also like