You are on page 1of 28

Arrays and Multidimensional

Arrays
Arrays and Multi dimensional
Arrays

SoftUni Team
Technical Trainers
Software University
http://softuni.bg
Table of Contents
1. Arrays in PHP
2. Array Manipulation
3. Multidimensional Arrays

2
Arrays in PHP
What are Arrays?
 An array is a ordered sequence of elements
 The order of the elements is fixed
 Can get the current length (count($array))
 In PHP arrays can change their size at runtime (add / delete)

Element of an array

0 1 2 3 4 Element
Array of 5 index
elements … … … … …

4
Creating Arrays
Initializing Arrays
 There are several ways to initialize an array in PHP:
 Using the array(elements) language construct:
$newArray = array(1, 2, 3); // [1, 2, 3]

 Using the array literal []:

$newArray = [7, 1, 5, 8]; // [7, 1, 5, 8]

 Using array_fill($startIndex, $count, $value):


$newArray = array_fill(0, 3, "Hi"); // ["Hi", "Hi", "Hi"]

6
Initializing Arrays – Examples
// Creating an empty array
$emptyArray = array();

// Creating an array with 10 elements of value 0.0


$myArray = array_fill(0, 10, 0.0);

// Clearing an array
$myArray = array();

// Adding string elements


$colors = ['green', 'blue', 'red', 'yellow', 'pink', 'purple'];

7
Accessing Array Elements
 Array elements are accessed by their key (index)
 Using the [] operator
 By default, elements are indexed from 0 to count($arr)-1

0 1 2 3 4
Apple Pear Peach Banana Melon

 Values can be accessed / changed by the [ ] operator


$fruits = ['Apple', 'Pear', 'Peach', 'Banana', 'Melon'];
echo $fruits[0]; // Apple
echo $fruits[3]; // Banana
8
Accessing Array Elements (2)
 Changing element values
$cars = ['BMW', 'Audi', 'Mercedes', 'Ferrari'];
echo $cars[0]; // BMW
$cars[0] = 'Opel';
print_r($cars); // Opel, Audi, Mercedes, Ferrari

 Iterating through an array


$teams = ['FC Barcelona', 'Milan', 'Manchester United',
'Real Madrid', 'Loko Plovdiv'];
for ($i = 0; $i < count($teams); $i++) {
echo $teams[$i];
}
9
Append to Array
 Arrays in PHP are dynamic (dynamically-resizable)
 Their size can be changed at runtime through append / insert / delete
 Appending elements at the end:
 array_push($array, $element1, $element2, …)
 Alternative syntax: $cars[] = 'Lada';

$months = array();
array_push($months, 'January', 'February', 'March');
$months[] = 'April';
// ['January', 'February', 'March', 'April']
10
Delete from Array
 unset($array[$index]) – removes element at given position
 Does NOT reorder indexes
$array = array(0, 1, 2, 3);
unset($array[2]); Indices remain
print_r($array); // prints the array unchanged
// Array ([0] => 0 [1] => 1 [3] => 3)

 Use array_splice() in case proper ordering is important

11
Delete / Insert in Array
 array_splice($array, $startIndex, $length) – removes the
elements in the given range
$names = array('Maria', 'John', 'Richard', 'George');
array_splice($names, 1, 2); // ['Maria', 'George']

 array_splice($array, $startIndex, $length, $element) –


removes the elements in given range and inserts an element
$names = array('Jack', 'Melony', 'Helen', 'David');
array_splice($names, 2, 0, 'Don');
// ['Jack', 'Melony', 'Don', 'Helen', 'David']
12
Displaying Arrays
 There are several ways of displaying the entire content of an array:
$names = ['Maria', 'John', 'Richard', 'Hailey'];

 print_r($names) – prints the array in human-readable form


Array ( [1] => Maria [2] => John [3] => Richard [4] => Hailey )

 var_export($names) – prints the array in array form


array ( 1 => 'Maria', 2 => 'John', 3 => 'Richard', 4 => 'Hailey', )

 echo json_encode($names) – prints the array as JSON string


["Maria","John","Richard","Hailey"]
13
Problem: Sum First and Last Array Elements
 You are given array of strings holding numbers
 Calculate and print the sum of the first and the last elements

20
5
30 60 15 2 4
10
40

$array = [20, 30, 40];


$array_num = count($array);
echo $arr[0] + $arr[$array_num - 1];

14
Problem: Print Array Elements
 Enter array elements from html form - array of strings holding
numbers - comma separated
 Print the array as follows

20
7
30 20 70 3 7 10
40 30 60 4 3 5 2 2
50 40 50 5 4
60
10
70
15
Multidimensional Arrays
Multidimensional Arrays
 A multidimensional array is an array containing one or more arrays
 Elements are accessed by double indexing: arr[][]

Element is in 'row' 0,
One main array 0 1 2 'column' 2,
whose elements
0 4 6 3 i.e. $arr[0][2]
are arrays
1 2 1 2 Each sub-array
6 7 9 contains its own
2 elements

17
Multidimensional Arrays – Example
 Printing a matrix of 5 x 4 numbers:
$rows = 5;
$cols = 4;
$count = 1;
$matrix = [];
for ($r = 0; $r < $rows; $r++) {
$matrix[$r] = [];
for ($c = 0; $c < $cols; $c++) {
$matrix[$r][$c] = $count++;
}
}
print_r($matrix);
18
Problem: Biggest Element in Matrix
 A matrix of numbers comes as array of strings
 Each string holds numbers (space separated)

 Find the biggest number

3 5 17 12 91 5 3 5 7 12
-1 7 4 33 6 22 -1 4 33 2 20 50 10
1 8 99 3 10 43 8 3 0 4 8 33 145

99 33 145
19
Solution: Biggest Element in Matrix
//TODO
$matrix = [[1,3,4],[7,6,14],[23,67,89]];
$biggestNum = $matrix[0][0];
foreach ($matrix as $row) { 1 3 4
7 6 14
foreach ($row as $column) { 23 67 89
if ($column > $biggestNum) {
$biggestNum = $column;
}
}
}
echo $biggestNum;
20
Problem: Biggest and Smallest Element in
Matrix
 A matrix of numbers comes as array of strings from input form
 Each string holds numbers (space separated)

 Number of columns should be entered by the user

 Find the biggest and smallest number


3 5 17 12 91 5 3 5 7 12
-1 7 4 33 6 22 -1 4 33 2 20 50 10
1 8 99 3 10 43 8 3 0 4 8 33 145

99 -1 33 -1 145 8
21
PHP - Sort Functions For Arrays
 sort() - sort arrays in ascending order
 rsort() - sort arrays in descending order
 asort() - sort associative arrays in ascending order, according to the
value
 ksort() - sort associative arrays in ascending order, according to the key
 arsort() - sort associative arrays in descending order, according to the
value
 krsort() - sort associative arrays in descending order, according to the
key
22
Sort Array in Ascending Order - sort()
 <?php
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);
?>

 BMW
Toyota
Volvo

23
Sort Array in Descending Order - rsort()
 <?php
$cars = array("Volvo", "BMW", "Toyota");
rsort($cars);
?>

 Volvo
Toyota
BMW

24
Sort Array (Ascending Order), According to
Value - asort()
 <?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
asort($age);
?>

 Key=Peter, Value=35
Key=Ben, Value=37
Key=Joe, Value=43

25
Sort Array (Ascending Order), According to Key -
ksort()
 <?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
ksort($age);
?>

 Key=Ben, Value=37
Key=Joe, Value=43
Key=Peter, Value=35

26
Sort Array (Descending Order), According to
Value - arsort()
 <?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
arsort($age);
?>

 Key=Joe, Value=43
Key=Ben, Value=37
Key=Peter, Value=35

27
Sort Array (Descending Order), According to Key
- krsort()
 <?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
krsort($age);
?>

 Key=Peter, Value=35
Key=Joe, Value=43
Key=Ben, Value=37

28

You might also like