Arrays and Multidimensional Arrays

Slides:



Advertisements
Similar presentations
Methods, Arrays, Lists, Dictionaries, Strings, Classes and Objects
Advertisements

Multidimensional Arrays, Sets, Dictionaries Processing Matrices, Multidimensional Arrays, Dictionaries, Sets SoftUni Team Technical Trainers Software University.
Forms Overview, Query string, Submitting arrays, PHP & HTML, Input types, Redirecting the user Mario Peshev Technical Trainer Software.
Sets, Dictionaries SoftUni Team Technical Trainers Software University
Lists and Matrices Lists: Variable-Size Arrays Matrices: Arrays of Arrays (Tables) SoftUni Team Technical Trainers Software University
First Steps in PHP Creating Very Simple PHP Scripts SoftUni Team Technical Trainers Software University
Stacks and Queues Processing Sequences of Elements SoftUni Team Technical Trainers Software University
Strings and Text Processing
Graphs and Graph Algorithms
Exporting and Importing Data
Auto Mapping Objects SoftUni Team Database Applications
Static Members and Namespaces
Functional Programming
Databases basics Course Introduction SoftUni Team Databases basics
Abstract Classes, Abstract Methods, Override Methods
Sets, Hash table, Dictionaries
Data Structures Course Overview SoftUni Team Data Structures
Introduction to MVC SoftUni Team Introduction to MVC
PHP MVC Frameworks Course Introduction SoftUni Team Technical Trainers
PHP Fundamentals Course Introduction SoftUni Team Technical Trainers
Reflection SoftUni Team Technical Trainers Java OOP Advanced
Linear Data Structures: Stacks and Queues
Classes, Properties, Constructors, Objects, Namespaces
Mocking tools for easier unit testing
Parsing JSON JSON.NET, LINQ-to-JSON
State Management Cookies, Sessions SoftUni Team State Management
EF Code First (Advanced)
PHP MVC Frameworks MVC Fundamentals SoftUni Team Technical Trainers
Processing Sequences of Elements
Heaps and Priority Queues
Entity Framework: Code First
Parsing XML XDocument and LINQ
Repeating Code Multiple Times
Basic Tree Data Structures
Data Definition and Data Types
Databases advanced Course Introduction SoftUni Team Databases advanced
Arrays, Lists, Stacks, Queues
Install and configure theme
Balancing Binary Search Trees, Rotations
Debugging and Troubleshooting Code
Entity Framework: Relations
Fast String Manipulation
Array and List Algorithms
Functional Programming
ASP.NET Razor Engine SoftUni Team ASP.NET MVC Introduction
MVC Architecture, Symfony Framework for PHP Web Apps
Processing Variable-Length Sequences of Elements
Combining Data Structures
Built-in Functions. Usage of Wildcards
Data Definition and Data Types
Multidimensional Arrays, Sets, Dictionaries
Extending functionality using Collections
Exporting and Importing Data
Making big SPA applications
Functional Programming
Exporting and Importing Data
CSS Transitions and Animations
Train the Trainers Course
Iterators and Comparators
Software Quality Assurance
Directives & Forms Capturing User Input SoftUni Team
Conditional Statements, Loops, Exit, Require
Polymorphism, Interfaces, Abstract Classes
Text Processing and Regex API
/^Hel{2}o\s*World\n$/
First-Class Functions
Files, Directories, Exceptions
CSS Transitions and Animations
Iterators and Generators
Multidimensional Arrays
Presentation transcript:

Arrays and Multidimensional Arrays SoftUni Team Technical Trainers Software University http://softuni.bg © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Table of Contents Array Manipulation Multidimensional Arrays Arrays in PHP Array Manipulation Multidimensional Arrays © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Questions sli.do #PHPFUND

Arrays in PHP

What are Arrays? 0 1 2 3 4 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 index Array of 5 elements …

Creating Arrays © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Initializing Arrays There are several ways to initialize an array in PHP: Using the array(elements) language construct: Using the array literal []: Using array_fill($startIndex, $count, $value): $newArray = array(1, 2, 3); // [1, 2, 3] $newArray = [7, 1, 5, 8]; // [7, 1, 5, 8] $newArray = array_fill(0, 3, "Hi"); // ["Hi", "Hi", "Hi"] © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

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']; © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Declaring PHP Arrays Live Demo © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Read and Modify Elements by Index Accessing Array Elements Read and Modify Elements by Index © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

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 Values can be accessed / changed by the [ ] operator 0 1 2 3 4 Apple Pear Peach Banana Melon $fruits = ['Apple', 'Pear', 'Peach', 'Banana', 'Melon']; echo $fruits[0]; // Apple echo $fruits[3]; // Banana © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Accessing Array Elements (2) Changing element values Iterating through an array $cars = ['BMW', 'Audi', 'Mercedes', 'Ferrari']; echo $cars[0]; // BMW $cars[0] = 'Opel'; print_r($cars); // Opel, Audi, Mercedes, Ferrari $teams = ['FC Barcelona', 'Milan', 'Manchester United', 'Real Madrid', 'Loko Plovdiv']; for ($i = 0; $i < count($teams); $i++) { echo $teams[$i]; }

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']

Indices remain unchanged Delete from Array unset($array[$index]) – removes element at given position Does NOT reorder indexes Use array_splice() in case proper ordering is important $array = array(0, 1, 2, 3); unset($array[2]); print_r($array); // prints the array // Array ([0] => 0 [1] => 1 [3] => 3) Indices remain unchanged

Delete / Insert in Array array_splice($array, $startIndex, $length) – removes the elements in the given range array_splice($array, $startIndex, $length, $element) – removes the elements in given range and inserts an element $names = array('Maria', 'John', 'Richard', 'George'); array_splice($names, 1, 2); // ['Maria', 'George'] $names = array('Jack', 'Melony', 'Helen', 'David'); array_splice($names, 2, 0, 'Don'); // ['Jack', 'Melony', 'Don', 'Helen', 'David']

Displaying Arrays There are several ways of displaying the entire content of an array: print_r($names) – prints the array in human-readable form var_export($names) – prints the array in array form echo json_encode($names) – prints the array as JSON string $names = ['Maria', 'John', 'Richard', 'Hailey']; Array ( [1] => Maria [2] => John [3] => Richard [4] => Hailey ) array ( 1 => 'Maria', 2 => 'John', 3 => 'Richard', 4 => 'Hailey', ) ["Maria","John","Richard","Hailey"] © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

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 30 40 60 5 10 15 2 4 $array = [20, 30, 40]; $array_num = count($array); echo $arr[0] + $arr[$array_num - 1];

Problem: Print Array Elements Enter array elements from html form - array of strings holding numbers - comma separated Print the array as follows 20 30 40 50 60 70 7 3 4 5 10 20 70 30 60 40 50 7 10 3 5 4 2 2

Practice: Accessing and Manipulating Arrays * Practice: Accessing and Manipulating Arrays Live Exercises in Class (Lab) (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

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, 'column' 2, i.e. $arr[0][2] One main array whose elements are arrays 0 1 2 1 2 4 6 3 2 1 7 9 Each sub-array contains its own elements © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

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); © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Multidimensional Arrays – Example (2) Printing a matrix as HTML table: <table border="1"> <?php for ($row = 0; $row < count($matrix); $row++) : ?> <tr> <?php for ($col = 0; $col < count($matrix[$row]); $col++) : ?> <td><?= htmlspecialchars($matrix[$row][$col]) ?></td> <?php endfor ?> </tr> </table> © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

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 -1 7 4 33 6 22 1 8 99 3 10 43 3 5 7 12 -1 4 33 2 8 3 0 4 20 50 10 8 33 145 99 33 145

Solution: Biggest Element in Matrix //TODO $matrix = [[1,3,4],[7,6,14],[23,67,89]]; $biggestNum = $matrix[0][0]; foreach ($matrix as $row) { foreach ($row as $column) { if ($column > $biggestNum) { $biggestNum = $column; } echo $biggestNum; 1 3 4 7 6 14 23 67 89

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 -1 7 4 33 6 22 1 8 99 3 10 43 3 5 7 12 -1 4 33 2 8 3 0 4 20 50 10 8 33 145 99 -1 33 -1 145 8

Practice: Multidimensional Arrays * Practice: Multidimensional Arrays Live Exercises in Class (Lab) (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

Summary An array is a ordered sequence of elements PHP supports arrays We have learned about classical and multidimensional arrays Many built-in array functions, e.g. sort() © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Arrays and Multidimensional Arrays https://softuni.bg/courses/php-basics/ © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

License This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" license Attribution: this work may contain portions from "PHP Manual" by The PHP Group under CC-BY license "PHP and MySQL Web Development" course by Telerik Academy under CC-BY-NC-SA license © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Free Trainings @ Software University Software University Foundation – softuni.org Software University – High-Quality Education, Profession and Job for Software Developers softuni.bg Software University @ Facebook facebook.com/SoftwareUniversity Software University @ YouTube youtube.com/SoftwareUniversity Software University Forums – forum.softuni.bg © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.