SlideShare a Scribd company logo
1 of 33
PHP Arrays
Outline
What are arrays ?
• Arrays are data structures that contain a group of elements
that are accessed through indexes.
• Usage :
<?php
$x = array( “banana”, “orange”, “mango”, 3, 4 );
echo $x[0]; // banana
echo $x[1]; // orange
echo $x[3]; // 3
?>
Ways to work with arrays
<?php
$arr = array( “banana”, “orange”);
$arr[4] = “mango”;
$arr[] = “tomato”;
var_dump($arr);
?>
Printing Arrays
• Use print_r() or var_dump() functions to output the
contents of an array.
<?php
$arr = array( “banana”, “orange”);
var_dump($arr ); // echoes the contents of the array
?>
Enumerative VS. Associative
• Enumerative arrays are indexed using only numerical
indexes.
<?php
$arr = array( “banana”, “orange”);
echo $arr[0]; // banana
?>
Enumerative VS. Associative
• Associative arrays allow the association of an arbitrary key
to every element.
<?php
$arr = array( ‘first’ => “banana”,
‘second’ =>“orange”);
echo $arr[‘first’]; // banana
?>
Multidimensional Arrays
• Multidimensional arrays are arrays that contain other
arrays.
<?php
$arr = array(
array( ‘burger’, 5, 15 ),
array( ‘cola’, 2, 25 ),
array( ‘Juice’, 3, 7 ),
);
echo $arr[0][0]; // burger
?>
Title Price Quantity
Burger 5 15
Cola 2 25
Juice 3 7
Array Iteration
• foreach loop :
Loop through arrays.
<?php
$arr1 = array(“mango" , “banana" , “tomato”);
foreach( $arr1 as $key => $value ){
echo $key . “ ----- > “ . $value . “<br/>”;
}
?>
Array Iteration
• We can use any other loop to go through arrays:
<?php
$arr1 = array(“mango" , “banana" , “tomato”);
for( $i =0; $i < count($arr1) ; $i++ ){
echo $i . “ ----- > “ . $arr1 [$i] . “<br/>”;
}
?>
Class Exercise
• Using arrays, write a PHP snippet that outputs the
following table data in an HTML table and calculate the
“total price” column values :
Title Price Quantity Total Price
Burger 5 10
Cola 2 4
Juice 3 7
Milk 2 6
Class Exercise - Solution
<?php
$array = array(
array( "name" => "Burger",
"price" => 5,
"quantity" => 10
),
array( "name" => "Cola",
"price" => 2,
"quantity" => 4
),
array( "name" => "Juice",
"price" => 3,
"quantity" => 7
),
array( "name" => "Milk",
"price" => 2,
"quantity" => 6
)
);
( Continued in the next slide )
Class Exercise - Solution
echo '<table border="1">';
echo "<tr><th>Name</th><th>Price</th><th>Quantity</th><th>Total Price</th></tr>";
foreach( $array as $row ){
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['price'] . "</td>";
echo "<td>" . $row['quantity'] . "</td>";
echo "<td>" . ( $row['price'] * $row['quantity'] ) . "</td>";
echo "</tr>";
}
echo "</table>";
?>
Array Operations
• PHP has a vast number of functions that allow us to do
many operations on arrays.
• For a complete reference of the functions, visit
http://php.net/manual/en/ref.array.php.
Array Comparison
• Equality ‘==‘:
True if the keys and values are equal.
<?php
$arr1 = array( “banana”, “mango”);
$arr2 = array( “banana”, “tomato”);
$arr3 = array( 1=> “mango”, 0=> “banana” );
if($arr1 == $arr2 ) // false
if($arr1 == $arr3 ) // true
?>
Array Comparison
• Identical ‘===‘:
True if the keys and values are equal and are in the same
order.
<?php
$arr1 = array( “banana”, “mango”);
$arr3 = array( 1=> “mango”, 0=> “banana” );
if($arr1 === $arr3 ) // false
?>
Array Comparison
• array array_diff ( array $array1 , array $array2 [, array
$ ... ] ) :
Returns an array containing all the entries from array1 that
are not present in any of the other arrays.
<?php
$arr1 = array( “banana”, “mango”, “lemon”);
$arr2 = array( “banana”, “mango”);
$diff = array_diff($arr1, $arr2); // lemon
?>
Counting Arrays
• int count ( mixed $var [, int $mode =
COUNT_NORMAL ] ) :
Count all elements in an array.
<?php
$arr1 = array( “banana”, “mango”, “lemon”);
echo count($arr1); // 3
?>
Searching Arrays
• mixed array_search ( mixed $needle , array $haystack [,
bool $strict ] ) :
Searches the array for a given value and returns the
corresponding key if successful.
<?php
$arr1 = array( “banana”, “mango”, “lemon”);
echo array_search( 'mango', $arr1 ); // 1
echo array_search( ‘strawberry’, $arr1 ); // false
?>
Deleting Items
• void unset ( mixed $var [, mixed $var [, mixed $... ]] ):
Unset a given variable.
<?php
$arr1 = array( “banana”, “mango”, “lemon”);
unset( $arr1[0] );
var_dump($arr1 ); // mango, lemon
?>
Arrays Flipping
• array array_flip ( array $trans ) :
Exchanges all keys with their associated values in an array
.
<?php
$arr1 = array(“mango" => 1, “banana" => 2);
$arr2 = array_flip($ arr1 );
var_dump($ arr2 ); // 1 => mango, 2=> banana
?>
Arrays Reversing
• array array_reverse ( array $array [, bool $preserve_keys
= false ] ) :
Return an array with elements in reverse order.
<?php
$arr1 = array(“mango" , “banana" , “tomato”);
$arr2 = array_reverse($ arr1 );
var_dump($ arr2 ); // tomato, banana, mango
?>
Merging Arrays
• array array_merge ( array $array1 [, array $array2 [, array $... ]] )
Merges the elements of one or more arrays together so
that the values of one are appended to the end of the
previous one. It returns the resulting array.
<?php
$array1 = array( 1, 2, 3 );
$array2 = array(4, 5, 6 );
$result = array_merge($array1, $array2);
print_r($result); // 1,2,3,4,5,6
?>
Array Sorting
• bool sort ( array &$array [, int $sort_flags =
SORT_REGULAR ] )
This function sorts an array. Elements will be arranged from lowest to
highest when this function has completed.
<?php
$fruits = array("lemon", "orange",
"banana", "apple");
sort($fruits);
var_dump($fruits); //apple, banana, lemon, orange
?>
Array Sorting
• bool rsort ( array &$array [, int $sort_flags = SORT_REGULAR ] )
This function sorts an array. Elements will be arranged from highest to
lowest when this function has completed.
<?php
$fruits = array("lemon", "orange",
"banana", "apple");
rsort($fruits);
var_dump($fruits); // orange, lemon, banana, apple
?>
Array Sorting
• bool asort ( array &$array [, int $sort_flags =
SORT_REGULAR ] )
Sorts an array from lowest to highest. This is used mainly when sorting
associative arrays.
<?php
$fruits = array( “one” => "lemon",
“two” => "orange",
“three” => "banana",
“four” => "apple");
asort($fruits);
var_dump($fruits); // four => apple, three => banana, one => lemon, two =>
orange
?>
Array Sorting
• bool arsort ( array &$array [, int $sort_flags =
SORT_REGULAR ] ) :
Sorts an array from highest to lowest. This is used mainly when sorting
associative arrays.
<?php
$fruits = array( “one” => "lemon",
“two” => "orange",
“three” => "banana",
“four” => "apple");
arsort($fruits);
var_dump($fruits); // two => orange, one => lemon, three =>
banana, four => apple
?>
Array Sorting
• bool ksort ( array &$array [, int $sort_flags = SORT_REGULAR ] )
Sorts an array by key, maintaining key to data correlations. This is
useful mainly for associative arrays.
<?php
$fruits = array("d"=>"lemon",
"a"=>"orange",
"b"=>"banana",
"c"=>"apple" );
ksort($fruits);
var_dump($fruits); // a => orange, b => banana, c => apple, d
=> lemon
?>
Array Sorting
• bool krsort ( array &$array [, int $sort_flags = SORT_REGULAR ] )
Sorts an array by key in reverse order, maintaining key to data
correlations. This is useful mainly for associative arrays.
<?php
$fruits = array( "d"=>"lemon",
"a"=>"orange",
"b"=>"banana",
"c"=>"apple" );
krsort($fruits);
var_dump($fruits); // d => lemon, c => apple, b => banana, a =>
orange
?>
Assignment
• Create a PHP function that takes an array as an argument and shows its
contents one on each line. This array may contain other arrays and these
arrays may contain others, etc. The function should display all the values
of these arrays. For example :
• If the array is like this :
$array = array(
1,
“Hello”,
array( 2, 3 ,4),
array(
5,
array( 6, 7, 8)
),
“No”
); ( Continued in the next slide )
Assignment
• The output should be like this :
1
Hello
2
3
4
5
6
7
8
No
What's Next?
• Strings.
Questions?

More Related Content

What's hot

What's hot (15)

03 Php Array String Functions
03 Php Array String Functions03 Php Array String Functions
03 Php Array String Functions
 
4.1 PHP Arrays
4.1 PHP Arrays4.1 PHP Arrays
4.1 PHP Arrays
 
PHP array 1
PHP array 1PHP array 1
PHP array 1
 
Chap 3php array part1
Chap 3php array part1Chap 3php array part1
Chap 3php array part1
 
PHP 101
PHP 101 PHP 101
PHP 101
 
Array in php
Array in phpArray in php
Array in php
 
Scripting3
Scripting3Scripting3
Scripting3
 
Climbing the Abstract Syntax Tree (php[world] 2019)
Climbing the Abstract Syntax Tree (php[world] 2019)Climbing the Abstract Syntax Tree (php[world] 2019)
Climbing the Abstract Syntax Tree (php[world] 2019)
 
Arrays in php
Arrays in phpArrays in php
Arrays in php
 
PHP PPT FILE
PHP PPT FILEPHP PPT FILE
PHP PPT FILE
 
07 php
07 php07 php
07 php
 
Wx::Perl::Smart
Wx::Perl::SmartWx::Perl::Smart
Wx::Perl::Smart
 
Laravel collections an overview - Laravel SP
Laravel collections an overview - Laravel SPLaravel collections an overview - Laravel SP
Laravel collections an overview - Laravel SP
 
Perl.Hacks.On.Vim
Perl.Hacks.On.VimPerl.Hacks.On.Vim
Perl.Hacks.On.Vim
 
Functional programming with php7
Functional programming with php7Functional programming with php7
Functional programming with php7
 

Viewers also liked

Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingAhmed Swilam
 
Class 8 - Database Programming
Class 8 - Database ProgrammingClass 8 - Database Programming
Class 8 - Database ProgrammingAhmed Swilam
 
Class 3 - PHP Functions
Class 3 - PHP FunctionsClass 3 - PHP Functions
Class 3 - PHP FunctionsAhmed Swilam
 
Class 1 - World Wide Web Introduction
Class 1 - World Wide Web IntroductionClass 1 - World Wide Web Introduction
Class 1 - World Wide Web IntroductionAhmed Swilam
 
Class 2 - Introduction to PHP
Class 2 - Introduction to PHPClass 2 - Introduction to PHP
Class 2 - Introduction to PHPAhmed Swilam
 
Class 5 - PHP Strings
Class 5 - PHP StringsClass 5 - PHP Strings
Class 5 - PHP StringsAhmed Swilam
 
Class 6 - PHP Web Programming
Class 6 - PHP Web ProgrammingClass 6 - PHP Web Programming
Class 6 - PHP Web ProgrammingAhmed Swilam
 
Geek Austin PHP Class - Session 4
Geek Austin PHP Class - Session 4Geek Austin PHP Class - Session 4
Geek Austin PHP Class - Session 4jimbojsb
 
S.G.Balaji Resume
S.G.Balaji ResumeS.G.Balaji Resume
S.G.Balaji ResumeBalaji Sg
 
PHP MVC Tutorial 2
PHP MVC Tutorial 2PHP MVC Tutorial 2
PHP MVC Tutorial 2Yang Bruce
 
Intro To Mvc Development In Php
Intro To Mvc Development In PhpIntro To Mvc Development In Php
Intro To Mvc Development In Phpfunkatron
 
Why to choose laravel framework
Why to choose laravel frameworkWhy to choose laravel framework
Why to choose laravel frameworkBo-Yi Wu
 
How to choose web framework
How to choose web frameworkHow to choose web framework
How to choose web frameworkBo-Yi Wu
 
Class and Objects in PHP
Class and Objects in PHPClass and Objects in PHP
Class and Objects in PHPRamasubbu .P
 
Enterprise-Class PHP Security
Enterprise-Class PHP SecurityEnterprise-Class PHP Security
Enterprise-Class PHP SecurityZendCon
 
REST API Best Practices & Implementing in Codeigniter
REST API Best Practices & Implementing in CodeigniterREST API Best Practices & Implementing in Codeigniter
REST API Best Practices & Implementing in CodeigniterSachin G Kulkarni
 

Viewers also liked (20)

Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented Programming
 
Class 8 - Database Programming
Class 8 - Database ProgrammingClass 8 - Database Programming
Class 8 - Database Programming
 
Class 3 - PHP Functions
Class 3 - PHP FunctionsClass 3 - PHP Functions
Class 3 - PHP Functions
 
Class 1 - World Wide Web Introduction
Class 1 - World Wide Web IntroductionClass 1 - World Wide Web Introduction
Class 1 - World Wide Web Introduction
 
Class 2 - Introduction to PHP
Class 2 - Introduction to PHPClass 2 - Introduction to PHP
Class 2 - Introduction to PHP
 
Class 5 - PHP Strings
Class 5 - PHP StringsClass 5 - PHP Strings
Class 5 - PHP Strings
 
Class 6 - PHP Web Programming
Class 6 - PHP Web ProgrammingClass 6 - PHP Web Programming
Class 6 - PHP Web Programming
 
Geek Austin PHP Class - Session 4
Geek Austin PHP Class - Session 4Geek Austin PHP Class - Session 4
Geek Austin PHP Class - Session 4
 
S.G.Balaji Resume
S.G.Balaji ResumeS.G.Balaji Resume
S.G.Balaji Resume
 
PHPUnit testing to Zend_Test
PHPUnit testing to Zend_TestPHPUnit testing to Zend_Test
PHPUnit testing to Zend_Test
 
PHP MVC Tutorial 2
PHP MVC Tutorial 2PHP MVC Tutorial 2
PHP MVC Tutorial 2
 
Intro To Mvc Development In Php
Intro To Mvc Development In PhpIntro To Mvc Development In Php
Intro To Mvc Development In Php
 
Functions in php
Functions in phpFunctions in php
Functions in php
 
Making web forms using php
Making web forms using phpMaking web forms using php
Making web forms using php
 
3 php forms
3 php forms3 php forms
3 php forms
 
Why to choose laravel framework
Why to choose laravel frameworkWhy to choose laravel framework
Why to choose laravel framework
 
How to choose web framework
How to choose web frameworkHow to choose web framework
How to choose web framework
 
Class and Objects in PHP
Class and Objects in PHPClass and Objects in PHP
Class and Objects in PHP
 
Enterprise-Class PHP Security
Enterprise-Class PHP SecurityEnterprise-Class PHP Security
Enterprise-Class PHP Security
 
REST API Best Practices & Implementing in Codeigniter
REST API Best Practices & Implementing in CodeigniterREST API Best Practices & Implementing in Codeigniter
REST API Best Practices & Implementing in Codeigniter
 

Similar to Class 4 - PHP Arrays

Array Methods.pptx
Array Methods.pptxArray Methods.pptx
Array Methods.pptxstargaming38
 
Php tips-and-tricks4128
Php tips-and-tricks4128Php tips-and-tricks4128
Php tips-and-tricks4128PrinceGuru MS
 
PHP and MySQL Tips and tricks, DC 2007
PHP and MySQL Tips and tricks, DC 2007PHP and MySQL Tips and tricks, DC 2007
PHP and MySQL Tips and tricks, DC 2007Damien Seguy
 
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...Dhivyaa C.R
 
PHP tips and tricks
PHP tips and tricks PHP tips and tricks
PHP tips and tricks Damien Seguy
 
PHP Array Functions.pptx
PHP Array Functions.pptxPHP Array Functions.pptx
PHP Array Functions.pptxKirenKinu
 
Hidden treasures of Ruby
Hidden treasures of RubyHidden treasures of Ruby
Hidden treasures of RubyTom Crinson
 
Marcs (bio)perl course
Marcs (bio)perl courseMarcs (bio)perl course
Marcs (bio)perl courseBITS
 
Introduction to Perl - Day 1
Introduction to Perl - Day 1Introduction to Perl - Day 1
Introduction to Perl - Day 1Dave Cross
 
Crafting Custom Interfaces with Sub::Exporter
Crafting Custom Interfaces with Sub::ExporterCrafting Custom Interfaces with Sub::Exporter
Crafting Custom Interfaces with Sub::ExporterRicardo Signes
 
Adventures in Optimization
Adventures in OptimizationAdventures in Optimization
Adventures in OptimizationDavid Golden
 
Chap 3php array part 3
Chap 3php array part 3Chap 3php array part 3
Chap 3php array part 3monikadeshmane
 
Refactor like a boss
Refactor like a bossRefactor like a boss
Refactor like a bossgsterndale
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to PerlDave Cross
 

Similar to Class 4 - PHP Arrays (20)

Array Methods.pptx
Array Methods.pptxArray Methods.pptx
Array Methods.pptx
 
Php tips-and-tricks4128
Php tips-and-tricks4128Php tips-and-tricks4128
Php tips-and-tricks4128
 
Intoduction to php arrays
Intoduction to php arraysIntoduction to php arrays
Intoduction to php arrays
 
PHP and MySQL Tips and tricks, DC 2007
PHP and MySQL Tips and tricks, DC 2007PHP and MySQL Tips and tricks, DC 2007
PHP and MySQL Tips and tricks, DC 2007
 
UNIT IV (4).pptx
UNIT IV (4).pptxUNIT IV (4).pptx
UNIT IV (4).pptx
 
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
 
PHP tips and tricks
PHP tips and tricks PHP tips and tricks
PHP tips and tricks
 
Chapter 2 wbp.pptx
Chapter 2 wbp.pptxChapter 2 wbp.pptx
Chapter 2 wbp.pptx
 
PHP Array Functions.pptx
PHP Array Functions.pptxPHP Array Functions.pptx
PHP Array Functions.pptx
 
Hidden treasures of Ruby
Hidden treasures of RubyHidden treasures of Ruby
Hidden treasures of Ruby
 
Php2
Php2Php2
Php2
 
Marcs (bio)perl course
Marcs (bio)perl courseMarcs (bio)perl course
Marcs (bio)perl course
 
Introduction to Perl - Day 1
Introduction to Perl - Day 1Introduction to Perl - Day 1
Introduction to Perl - Day 1
 
Chap 3php array part4
Chap 3php array part4Chap 3php array part4
Chap 3php array part4
 
Crafting Custom Interfaces with Sub::Exporter
Crafting Custom Interfaces with Sub::ExporterCrafting Custom Interfaces with Sub::Exporter
Crafting Custom Interfaces with Sub::Exporter
 
Adventures in Optimization
Adventures in OptimizationAdventures in Optimization
Adventures in Optimization
 
Chap 3php array part 3
Chap 3php array part 3Chap 3php array part 3
Chap 3php array part 3
 
Refactor like a boss
Refactor like a bossRefactor like a boss
Refactor like a boss
 
Php & my sql
Php & my sqlPhp & my sql
Php & my sql
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 

Recently uploaded

How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...itnewsafrica
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...itnewsafrica
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observabilityitnewsafrica
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesBernd Ruecker
 

Recently uploaded (20)

How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architectures
 

Class 4 - PHP Arrays

  • 3. What are arrays ? • Arrays are data structures that contain a group of elements that are accessed through indexes. • Usage : <?php $x = array( “banana”, “orange”, “mango”, 3, 4 ); echo $x[0]; // banana echo $x[1]; // orange echo $x[3]; // 3 ?>
  • 4. Ways to work with arrays <?php $arr = array( “banana”, “orange”); $arr[4] = “mango”; $arr[] = “tomato”; var_dump($arr); ?>
  • 5. Printing Arrays • Use print_r() or var_dump() functions to output the contents of an array. <?php $arr = array( “banana”, “orange”); var_dump($arr ); // echoes the contents of the array ?>
  • 6. Enumerative VS. Associative • Enumerative arrays are indexed using only numerical indexes. <?php $arr = array( “banana”, “orange”); echo $arr[0]; // banana ?>
  • 7. Enumerative VS. Associative • Associative arrays allow the association of an arbitrary key to every element. <?php $arr = array( ‘first’ => “banana”, ‘second’ =>“orange”); echo $arr[‘first’]; // banana ?>
  • 8. Multidimensional Arrays • Multidimensional arrays are arrays that contain other arrays. <?php $arr = array( array( ‘burger’, 5, 15 ), array( ‘cola’, 2, 25 ), array( ‘Juice’, 3, 7 ), ); echo $arr[0][0]; // burger ?> Title Price Quantity Burger 5 15 Cola 2 25 Juice 3 7
  • 9. Array Iteration • foreach loop : Loop through arrays. <?php $arr1 = array(“mango" , “banana" , “tomato”); foreach( $arr1 as $key => $value ){ echo $key . “ ----- > “ . $value . “<br/>”; } ?>
  • 10. Array Iteration • We can use any other loop to go through arrays: <?php $arr1 = array(“mango" , “banana" , “tomato”); for( $i =0; $i < count($arr1) ; $i++ ){ echo $i . “ ----- > “ . $arr1 [$i] . “<br/>”; } ?>
  • 11. Class Exercise • Using arrays, write a PHP snippet that outputs the following table data in an HTML table and calculate the “total price” column values : Title Price Quantity Total Price Burger 5 10 Cola 2 4 Juice 3 7 Milk 2 6
  • 12. Class Exercise - Solution <?php $array = array( array( "name" => "Burger", "price" => 5, "quantity" => 10 ), array( "name" => "Cola", "price" => 2, "quantity" => 4 ), array( "name" => "Juice", "price" => 3, "quantity" => 7 ), array( "name" => "Milk", "price" => 2, "quantity" => 6 ) ); ( Continued in the next slide )
  • 13. Class Exercise - Solution echo '<table border="1">'; echo "<tr><th>Name</th><th>Price</th><th>Quantity</th><th>Total Price</th></tr>"; foreach( $array as $row ){ echo "<tr>"; echo "<td>" . $row['name'] . "</td>"; echo "<td>" . $row['price'] . "</td>"; echo "<td>" . $row['quantity'] . "</td>"; echo "<td>" . ( $row['price'] * $row['quantity'] ) . "</td>"; echo "</tr>"; } echo "</table>"; ?>
  • 14. Array Operations • PHP has a vast number of functions that allow us to do many operations on arrays. • For a complete reference of the functions, visit http://php.net/manual/en/ref.array.php.
  • 15. Array Comparison • Equality ‘==‘: True if the keys and values are equal. <?php $arr1 = array( “banana”, “mango”); $arr2 = array( “banana”, “tomato”); $arr3 = array( 1=> “mango”, 0=> “banana” ); if($arr1 == $arr2 ) // false if($arr1 == $arr3 ) // true ?>
  • 16. Array Comparison • Identical ‘===‘: True if the keys and values are equal and are in the same order. <?php $arr1 = array( “banana”, “mango”); $arr3 = array( 1=> “mango”, 0=> “banana” ); if($arr1 === $arr3 ) // false ?>
  • 17. Array Comparison • array array_diff ( array $array1 , array $array2 [, array $ ... ] ) : Returns an array containing all the entries from array1 that are not present in any of the other arrays. <?php $arr1 = array( “banana”, “mango”, “lemon”); $arr2 = array( “banana”, “mango”); $diff = array_diff($arr1, $arr2); // lemon ?>
  • 18. Counting Arrays • int count ( mixed $var [, int $mode = COUNT_NORMAL ] ) : Count all elements in an array. <?php $arr1 = array( “banana”, “mango”, “lemon”); echo count($arr1); // 3 ?>
  • 19. Searching Arrays • mixed array_search ( mixed $needle , array $haystack [, bool $strict ] ) : Searches the array for a given value and returns the corresponding key if successful. <?php $arr1 = array( “banana”, “mango”, “lemon”); echo array_search( 'mango', $arr1 ); // 1 echo array_search( ‘strawberry’, $arr1 ); // false ?>
  • 20. Deleting Items • void unset ( mixed $var [, mixed $var [, mixed $... ]] ): Unset a given variable. <?php $arr1 = array( “banana”, “mango”, “lemon”); unset( $arr1[0] ); var_dump($arr1 ); // mango, lemon ?>
  • 21. Arrays Flipping • array array_flip ( array $trans ) : Exchanges all keys with their associated values in an array . <?php $arr1 = array(“mango" => 1, “banana" => 2); $arr2 = array_flip($ arr1 ); var_dump($ arr2 ); // 1 => mango, 2=> banana ?>
  • 22. Arrays Reversing • array array_reverse ( array $array [, bool $preserve_keys = false ] ) : Return an array with elements in reverse order. <?php $arr1 = array(“mango" , “banana" , “tomato”); $arr2 = array_reverse($ arr1 ); var_dump($ arr2 ); // tomato, banana, mango ?>
  • 23. Merging Arrays • array array_merge ( array $array1 [, array $array2 [, array $... ]] ) Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array. <?php $array1 = array( 1, 2, 3 ); $array2 = array(4, 5, 6 ); $result = array_merge($array1, $array2); print_r($result); // 1,2,3,4,5,6 ?>
  • 24. Array Sorting • bool sort ( array &$array [, int $sort_flags = SORT_REGULAR ] ) This function sorts an array. Elements will be arranged from lowest to highest when this function has completed. <?php $fruits = array("lemon", "orange", "banana", "apple"); sort($fruits); var_dump($fruits); //apple, banana, lemon, orange ?>
  • 25. Array Sorting • bool rsort ( array &$array [, int $sort_flags = SORT_REGULAR ] ) This function sorts an array. Elements will be arranged from highest to lowest when this function has completed. <?php $fruits = array("lemon", "orange", "banana", "apple"); rsort($fruits); var_dump($fruits); // orange, lemon, banana, apple ?>
  • 26. Array Sorting • bool asort ( array &$array [, int $sort_flags = SORT_REGULAR ] ) Sorts an array from lowest to highest. This is used mainly when sorting associative arrays. <?php $fruits = array( “one” => "lemon", “two” => "orange", “three” => "banana", “four” => "apple"); asort($fruits); var_dump($fruits); // four => apple, three => banana, one => lemon, two => orange ?>
  • 27. Array Sorting • bool arsort ( array &$array [, int $sort_flags = SORT_REGULAR ] ) : Sorts an array from highest to lowest. This is used mainly when sorting associative arrays. <?php $fruits = array( “one” => "lemon", “two” => "orange", “three” => "banana", “four” => "apple"); arsort($fruits); var_dump($fruits); // two => orange, one => lemon, three => banana, four => apple ?>
  • 28. Array Sorting • bool ksort ( array &$array [, int $sort_flags = SORT_REGULAR ] ) Sorts an array by key, maintaining key to data correlations. This is useful mainly for associative arrays. <?php $fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple" ); ksort($fruits); var_dump($fruits); // a => orange, b => banana, c => apple, d => lemon ?>
  • 29. Array Sorting • bool krsort ( array &$array [, int $sort_flags = SORT_REGULAR ] ) Sorts an array by key in reverse order, maintaining key to data correlations. This is useful mainly for associative arrays. <?php $fruits = array( "d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple" ); krsort($fruits); var_dump($fruits); // d => lemon, c => apple, b => banana, a => orange ?>
  • 30. Assignment • Create a PHP function that takes an array as an argument and shows its contents one on each line. This array may contain other arrays and these arrays may contain others, etc. The function should display all the values of these arrays. For example : • If the array is like this : $array = array( 1, “Hello”, array( 2, 3 ,4), array( 5, array( 6, 7, 8) ), “No” ); ( Continued in the next slide )
  • 31. Assignment • The output should be like this : 1 Hello 2 3 4 5 6 7 8 No