You are on page 1of 37

PHP Arrays (4 of 5) Slide 1

CHAPTER 2:
PHP Arrays (4 of 5)
Topics covered:-
Arrays in PHP
Accessing elements of an array
Using loop to access array elements
Creating multidimensional arrays
Using functions to manipulate arrays – merging, sorting
and etc.

AMIT 2043 Web Systems and Technologies


PHP Arrays (4 of 5) Slide 2

Variables vs Arrays
• Recall that a variable is a container that holds a value.
• Unfortunately, variables only allows to hold a value. If you use the same
variable to declare many values, only the last value declared will be
registered and recognized by that variable name.
• Imagine you would like to store more than one value referenced by a
single name, a variable is not feasible to be used.
• Solution:-
Declare, initialize and use array instead.

AMIT 2043 Web Systems and Technologies


PHP Arrays (4 of 5) Slide 3

Introduction to Arrays
• Use array to work with a large amount of data.

• For example, if you wish to keep a record of 100 product names


available in your inventory. Using variable, you have to create 100
product names, $product1, $product2, .. $product100. Meaning to say,
you have to create product name for 100 times.

• The above situation can be easily solved by just declaring an array name
called $product that holds information of all product at once.

AMIT 2043 Web Systems and Technologies


PHP Arrays (4 of 5) Slide 4

Types of Arrays
• PHP supports two types of arrays:-
• Index arrays
• Associative arrays

$studentName $testMark
[5] Herman Herman 100

[4] Gillian Gillian 100

[3] Frankie Frankie 97

[2] Candy Candy 72

[1] Beatrice Beatrice 68

[0] Allan Allan 63

Index Element Value key Element Value


AMIT 2043 Web Systems and Technologies
PHP Arrays (4 of 5) Slide 5

Indexed Array
• These are arrays where each element is referenced by a numeric key /
index.
• The first index / key starts from zero (0).
• The second index / key is one (1) and so on…..
Index/Key Element / Value

0 23.50

1 40.00

2 100.99

3 56.99

4 88.20

5 97.25

• The above array is of size 6 and store a list of product prices of type
double / float.
AMIT 2043 Web Systems and Technologies
PHP Arrays (4 of 5) Slide 6

Associative Array
• This type of array is also called a hash / map.
• Instead of numeric key indexes, associative array is referenced by a
string index.
Index/Key Element / Value

jimmyChoo 590.00

louisVuitton 1200.00

prada 100.99

valentino 475.00

gucci 88.20

chloe 97.00

• The above array is of size 6 and store a list of handbag prices of type
double / float.

AMIT 2043 Web Systems and Technologies


PHP Arrays (4 of 5) Slide 7

Declaring Index and Associative Arrays


• Using the PHP built-in array() construct.
• Example of an Index array construct:-
$productPrice = array(23.50, 12.99, 68.89, 25.00);

• Example of an Associative array construct:-


$handBagPrice = array(“jimmyChoo” => 590.00,
“chloe” => 250.00,
“valentino” => 200.00,
“luoisVuitton” => 1200,
“prada” => 20.00);
Note: an array can have a mix of different types of elements, say an array
contains string and integer elements.

AMIT 2043 Web Systems and Technologies


PHP Arrays (4 of 5) Slide 8

Accessing and Changing Array Elements


• All the above can be done by using the index / key / string index of an array.
• Given the array declared and initialize this way:
$car = array(); //an empty array
$car[“brand”] = “Volkswagen”;
$car[“model”] = “Polo”;
$car[“made”] = “German”;
• Example: Retrieving an array element
echo $car[“brand”]; //display Volkswagen
• Example: Changing the element value
$car[“model”] = “Beetle”;
echo $car[“model”]; //display Beetle

• Example: Add new element at the end of the array


$car[“capacity”] = “3000”;

AMIT 2043 Web Systems and Technologies


PHP Arrays (4 of 5) Slide 9

Output an Entire Array Using print_r()


Function
• Of course, printing array element can be achieved just by using the
normal print() and echo() function.
• However, the different using the normal print() and echo() functions as
compared to print_r() function is just that print() and echo() works with
one variable value at a time. With this, a for loop is necessary to print all
elements of the indexed array.
• By using print_r(), this function accepts the array name to retrieve all
elements in the array for your inspection. The array elements printed
shows both key and value side-by-side.

Refer to example code workingWithArrays

AMIT 2043 Web Systems and Technologies


PHP Arrays (4 of 5) Slide 10

Extract a Range of Element Using


array_slice() Function
• Syntax:
array_slice(<array to slice>, <start index>, <length>,
<preserve or not to preserve the index>)
• Example:
$members = array("Alan", "Bernard", "Candy", "Daniel", "Eric");
print_r(array_slice($members, 1, 2));
• Resulted Output:-
Array([0]=>Bernard [1]=>Candy)

Note: The original array left untouched. However, the index of Bernard and
Candy changes from [1] and [2] to [0] and [1] instead.
In order to preserve the original index of Bernard and Candy, use the optional
fourth argument, like:-
print_r(array_slice($members,
AMIT 2043 Web Systems and Technologies 1, 2, true));
PHP Arrays (4 of 5) Slide 11

count() Function –Size of an Array


• In C programming language, we use sizeof() function.
• Example:
int arr[] = {1,2,3,4,5};
printf(“Length: %d”, sizeof(arr));

• In PHP, we use count() function.


• Example:
echo count($members); //display 5

• count() function returns an integer representing the size / length of the


array.

AMIT 2043 Web Systems and Technologies


PHP Arrays (4 of 5) Slide 12

Stepping Through an Array


Function Description

current() Returns the value of the current element pointed by the pointer, without changing the pointer
position.

key() Returns the index of the current element pointed to by the pointer, without changing the pointer
position.

next() Moves the pointer forward to the next element, and returns that element’s value.

prev() Moves the pointer backward to the previous element, and returns that element’s value.

end() Moves the pointer to the last element in the array, and returns that element’s value.

reset() Moves the pointer to the first element in the array, and returns that element’s value.

Refer to example code workingWithArrays


AMIT 2043 Web Systems and Technologies
PHP Arrays (4 of 5) Slide 13

Stepping Through an Array


• Take a couple of minutes to understand the program segment.
• You will then noticed that:-
• Each of the above functions only takes in one argument which is the array.
• These functions returned either the element’s value or the index / key.
• It will also returned false for the element could not be found. This is the case
when:-
• Current position of the key is 0 and the prev() function is called.
• Current position of the key is the end of the array and the next() function is called.

NOTE: Recalled that when a function returned a 1 is referred to as true and all other
value returned is referred to as false.

Refer to example code workingWithArrays


AMIT 2043 Web Systems and Technologies
PHP Arrays (4 of 5) Slide 14

foreach() Loop
• It is used when you want to travers the entire array sequentially from the
beginning of the array until to the end of the array.
• Syntax:
foreach(<array name>
as
<any variable to capture element’s value at each loop>){
// do something with each array element’s value}

• Example:-
foreach($members as $value){
echo $value; //just print each array element’s value
}

Refer to example code workingWithArrays


AMIT 2043 Web Systems and Technologies
PHP Arrays (4 of 5) Slide 15

foreach() Loop
• The previous example only been able to access each array element’s value.

• If you wish to access value + key, use the example below:-

• Example:-
foreach($members as $key => $value){
//print each array index and its associated element’s value
echo $key . “ => ” . $value . “<br>”;
}

Refer to example code workingWithArrays


AMIT 2043 Web Systems and Technologies
PHP Arrays (4 of 5) Slide 16

foreach() Loop
• If you wish to change each element’s value in the array in the foreach loop,
just pass the value as a reference parameter using the symbol ampersand (&).

• Syntax:
• Example:-
foreach($productPrice as &$value){
$value += 5; //add 5 to every product price
}
print_r($productPrice); //print all array elements to inspect changes

AMIT 2043 Web Systems and Technologies


PHP Arrays (4 of 5) Slide 17

Multidimensional Array
• Below shows a two-dimensional array with 5 rows and 4 columns.

[0][0] [0][1] [0][2] [0][3]

[1][0] [1][1] [1][2] [1][3]

[2][0] [2][1] [2][2] [2][3]

[3][0] [3][1] [3][2] [3][3]

[4][0] [4][1] [4][2] [4][3]

Refer to example code twoDimensionalArray

AMIT 2043 Web Systems and Technologies


$car = array(); //empty array echo "<pre>";
PHP Arrays (4 of 5) Slide 18
//first-level print_r($car);
echo "</pre>";
$car = array(
?>
//second-level
Resulted Output:-
array("brand" => "Mitsubishi",
"model" => "Adventure",
"made" => "Japan",
"year" => 1997)
,
array("brand" => "Mini",
"model" => "Clubman",
"made" => "British",
"year" => 2008)
,
array("brand" => "Kia",
"model" => "Sorento",
"made" => "South Korea",
"year" => 2002)
);
AMIT 2043 Web Systems and Technologies
PHP Arrays (4 of 5) Slide 19

• What can you understand from the above code example?


• (1) The first level array is referenced by $car with three sub-arrays.
• (2) Each sub-arrays can be retrieved by $car[0], $car[1] and $car[2] using
indexes.
• (3) To retrieve the values “Mitsubishi”, “Mini”, “Kia”, we can use $car[0]
[“brand”], $car[1][“brand”] and $car[2][“brand”].
• Conclusion:-
• first-level is an array.
• Second-level is also an array.

AMIT 2043 Web Systems and Technologies


PHP Arrays (4 of 5) Slide 20

Accessing Elements of Multidimensional Array


• You have learned how to access each array element’s value from a
simple array.
• You have also learned the concept of using foreach() loop.
• Let’s study the code example below:-

$numCar = 0; An array

foreach($car as $individualCar){
echo "Car #" . $numCar . "<br>";
echo "================<br>";
$numCar++;

foreach($individualCar as $key => $value){


echo $key . " => " . $value . "<br>";
}
}
AMIT 2043 Web Systems and Technologies
PHP Arrays (4 of 5) Slide 21

Manipulating Arrays
• This section covers some common and useful array-processing functions.

• These functions include:-


• Sorting
• Adding and Removing array elements
• Merging arrays together
• Converting between array and string
• Converting array to a list of variables

AMIT 2043 Web Systems and Technologies


PHP Arrays (4 of 5) Slide 22

Sorting
• Recall that array has two types:-
• Indexed Array
• Associative Array
• In order to perform sorting, PHP does provide sorting functions to treat
these two types of arrays.
• These sorting functions include:-
• sort() and rsort() – For sorting indexed array
• asort() and arsort() – For sorting associative array
• ksort() and krsort() – For sorting associative array by keys
• array_multisort() – sorting multiple arrays at once including multidimensional
arrays

AMIT 2043 Web Systems and Technologies


PHP Arrays (4 of 5) Slide 23

sort() and rsort() – Indexed Array


• sort() – to sort values in ascending.
• rsort() – to sort values in descending.
• Example:-
$members = array("Alan", "Bernard", "Candy", "Daniel", "Eric");
sort($members);
print_r($members);

rsort($members);
print_r($members);

• Resulted Output:

AMIT 2043 Web Systems and Technologies


PHP Arrays (4 of 5) Slide 24

asort() and arsort() – Associative Array


• asort() – to sort values in ascending of associative array.
• arsort() – to sort values in descending of associative array.
• Example:-
$handBag = array("artist" => "Jimmy Choo", "price" => 1000.00,
"manufactured" => "Vietname", "year" => 2002,
"code" => "JCV1K");
asort($handBag);
print_r($handBag);
echo "<br>";
arsort($handBag);
print_r($handBag);
• Resulted Output:

AMIT 2043 Web Systems and Technologies


PHP Arrays (4 of 5) Slide 25

ksort() and krsort() – Associative Array - key


• ksort() – to sort key in ascending of associative array.
• krsort() – to sort key in descending of associative array.
• Example:-
$handBag = array("artist" => "Jimmy Choo", "price" => 1000.00,
"manufactured" => "Vietname", "year" => 2002,
"code" => "JCV1K");
ksort($handBag);
print_r($handBag);
echo "<br>";
krsort($handBag);
print_r($handBag);
• Resulted Output:

AMIT 2043 Web Systems and Technologies


PHP Arrays (4 of 5) Slide 26

array_multisort() Function
• Can be used to sort more than one single-dimensional at the same time.
• Can also be used to sort multidimensional array.

• Syntax for multiple one-dimensional array:


array_multisort(<firstArray>, <secondArray>, <thirdArray>….);

• Syntax for multidimensional array:


array_multisort(<multidimensionalArray>);

• With the above syntax, array_multisort() function will sort all arrays
according to the first sorted array element’s values.

Refer to example code twoDimensionalArray


AMIT 2043 Web Systems and Technologies
PHP Arrays (4 of 5) Slide 27

Adding and Removing Array Elements


• Recall that we can simply add an additional array element by specifying
the array name with the square bracket.
• In addition, PHP support for another 5 powerful functions to add and
remove array elements:-
Functions Descriptions

array_unshift() Add elements at the start of the array

array_shift() Removes the first element from the start of the array

array_push() Add elements at the end of the array

array_pop() Removes the last element from the end of the array

array_splice() Removes / Add elements at any point in the array

AMIT 2043 Web Systems and Technologies


PHP Arrays (4 of 5) Slide 28

array_unshift() and array_shift() functions


$mobileWebApps = array("Google+", "Picasa Web Albums",
"Google Wallet");
echo array_unshift($mobileWebApps, "Drive", "Gmail",
"Google Latitude"); //returned 6
print_r($mobileWebApps);
echo array_shift($mobileWebApps); //returned 5
echo array_shift($mobileWebApps); //returned 4
echo array_shift($mobileWebApps); //returned 3
echo array_shift($mobileWebApps); //returned 2
echo "<br>";
print_r($mobileWebApps);

Note: indexes will be rearranged accordingly.

AMIT 2043 Web Systems and Technologies


PHP Arrays (4 of 5) Slide 29

array_push() and array_pop() functions


$andriodCodeName = array("Cupcake", "Donut", "Eclair",
"Froyo");

echo array_push($andriodCodeName,
"Gingerbread",
"Honeycomb",
"Ice cream Sandwich",
"Jelly Bean"); //returned 8

array_pop($andriodCodeName); //call array_pop #1


array_pop($andriodCodeName); //call array_pop #1
array_pop($andriodCodeName); //call array_pop #1

echo count($andriodCodeName); //returned 5

AMIT 2043 Web Systems and Technologies


PHP Arrays (4 of 5) Slide 30

array_splice() function
• Recall that array_splice() function is to add/remove element at any
position in the array at the same time.
• Syntax:
array_splice(<array>, <start index>, <length>,
<array to add>) //returns an array
• Explanation:-
• If length is not specified, array_splice() will remove element from the
start index until the last element.

AMIT 2043 Web Systems and Technologies


PHP Arrays (4 of 5) Slide 31

array_splice() function
• Example:-
$oriArray = array("Lake Toba", "Bali");
$addArray = array("Jakarta","Aceh");
print_r(array_splice($oriArray, 0)); //print empty array
print_r($oriArray); //print the array with new elements

• This function works well with indexed array but not useful working with
associative arrays.
• Why? The reason being that the associative array key are not retained when
new items are added. Instead, array_splice() function will remove the key of
that newly added element(s) and follow the original indexes.

Refer to example code twoDimensionalArray


AMIT 2043 Web Systems and Technologies
PHP Arrays (4 of 5) Slide 32

array_splice() function
• Example:-

$placesArray = array("Lake Toba", "Bali");


$addNewArray = array("Highlight" => "Bandung",
"Year" => 2013);
array_splice($placesArray, 1, 1, $addNewArray);
echo "<pre>";
print_r($placesArray);
echo "</pre>";

Refer to example code twoDimensionalArray


AMIT 2043 Web Systems and Technologies
PHP Arrays (4 of 5) Slide 33

Merging Arrays Together


• The function accepts a list of arrays and returned the newly merged array
without affecting the original arrays.
• Syntax:-
array_merge(<array1>, <array2>, …);
• Example:-
$janMovie = array("Broken City", "The Last Stand",
"Hansel and Gretel");
$febMovie = array("Beautiful Creatures", "Die Hard 5",
"Escape from planet earth");
$marMovie = array("GI Joe 2", "The Host",
"The place beyond the pine");
echo "<pre>";
print_r(array_merge($janMovie, $febMovie, $marMovie));
echo "</pre>";

AMIT 2043 Web Systems and Technologies


PHP Arrays (4 of 5) Slide 34

array_merge() with associative array


• Example:
$famousFalls = array("Country" => "New York",
"Title" => "Niagaria Falls");
$anotherFalls = array("Country" => "New York",
"Title" => "Ashley Falls");
echo "<pre>";
print_r(array_merge($famousFalls, $anotherFalls));
echo "</pre>";

• By analyzing the output returned, justify what does array_merge() function


does to associative arrays?

AMIT 2043 Web Systems and Technologies


PHP Arrays (4 of 5) Slide 35

Converting Between Arrays and Strings


• Using implode() or explode() function.
• String => Array, use explode() function.
• Explode function takes in a string and split a long string into chunks
following a specified delimiter.
• Array => String, use implode() function.
• Implode function takes in an array and split text in the array following a
specified delimiter.
• Example:-
$days = "Sun-Mon-Tue-Wed-Thu-Fri-Sat";
$dayArray = explode("-", $days);
print_r($dayArray);
echo "<br>";
echo implode($dayArray, "-");

AMIT 2043 Web Systems and Technologies


PHP Arrays (4 of 5) Slide 36

Converting Array to a List of Variables


• The conventional way to get each element from an array and put them
into variables simply assigned the array name and its index into a
variable.
• Example:-
$janMovie = array("Broken City", "The Last Stand",
"Hansel and Gretel");
$movie1 = $janMovie[0];
$movie2 = $janMovie[1];
$movie3 = $janMovie[2];

However, the above can be cut short and be done with list() function.

AMIT 2043 Web Systems and Technologies


PHP Arrays (4 of 5) Slide 37

Examining list() Function


• Use to convert individual array element into a list of variables.
• Syntax:
list(<var1>, <var2>, …) = array
• Example:
$book = array("PHP Web Programming", "Wrox", 2013);
list($title, $publisher, $year) = $book;

echo $title . "<br>";


echo $publisher . "<br>";
echo $year . "<br>";

AMIT 2043 Web Systems and Technologies

You might also like