SlideShare a Scribd company logo
Chapter 19-2
PHP
LECTUR 5:
ARRAYS IN
PHP
CHAPTER 19
Web-Based Design
IT210
1
OBJECTIVES
By the end of this lecture student will be able to:
 Understanding array concept.
 Creating arrays
 Understanding the difference types of array
 Dealing with arrays by printing ,adding , deleting ,changing
elements from array
2
OUTL
INE
3
Arrays in PHP.
Types of Array.
Initializing and
Manipulating Arrays.
ARRAYS IN PHP
 An array is a group of data type which is used to store multiple values in a
single variable.
 Array names: like other variables, begin with the $ symbol.
 Individual array elements are accessed by following the array’s variable
name with an index enclosed in square brackets ([]).
 Array index: The location of an element in an array is known as its index.
The elements in an ordered array are arranged in ascending numerical
order starting with zero—the index of the first array element is 0, the index
of the second is 1, and so on.
4
ARRAYS IN PHP
From the picture:
 What is the array
name?
 How many element
does it contain ?
 What is the index of
"Fish" element ?
5
$my_array= [7, "24" , "Fish", "hat stand"]
ARRAY TYPES
 There are three types of arrays in PHP, which are as follows:
6
•It use integer/numbers as their index number to identify each item of the array.
• Array element index start with 0, the next is 1, and so on.
1.Numeric Index Array (ordered array):
• Array inside another array
Nested Array:
• Arrays with nonnumeric index
Associative Array:
CREATING ARRAYS IN PHP
There are two ways to create an array in PHP:
1. Creating Arrays with array() function
e.g: $my_array = array(0, 1, 2);
2. Creating Arrays with Short Syntax
e.g: $my_array = [0, 1, 2];
7
CREATING ARRAYS WITH array()
FUNCTION
 Constructing ordered arrays with a built-in PHP function: array().
 The array() function returns an array.
 Each of the arguments with which the function was invoked becomes
an element in the array (in the order they were passed in).
8
$my_array = array(0, 1, 2);
$string_array = array("first element", "second element");
$mixed_array = array(1, "chicken", 78.2, "bubbles are
crazy!");
To read more about built-in PHP function: array().
CREATING ARRAYS WITH SHORT
SYNTAX
 Creating an array is also possible by wrapping comma-separated
elements in square brackets ([ ]).
9
$my_array = [0, 1, 2];
$string_array = ["first element", " second element "];
$mixed_array = [1, "chicken", 78.2, "bubbles are crazy! "];
count() FUNCTION
 Function count returns the total number of elements in the array.
10
$my_array = [0, 1, 2];
$string_array = ["first element", " second element "];
$mixed_array = [1, "chicken", 78.2, "bubbles are crazy! "];
echo count($my_array);
echo count($string_array);
echo count($mixed_array);
To read more built-in PHP count() function
output 3
output 2
output 4
PRINTING ARRAYS WITH print_r()
FUNCTION
 Since arrays are a more complicated data type than strings or integers,
using echo won’t have the desired result:
11
$my_array = [0, 1, 2];
echo $my_array;
print_r() function: is PHP built-in functions that print the contents of the
array
$my_array = [0, 1, 2];
print_r($my_array);
Echo “<br>”;
This will output the
array in the following
format:
Array
(
[0 ]=> 0
[1] => 1
[2] => 2
)
To read more about built-in print_r() function
This will output the
array:
array
PRINTING ARRAYS WITH implode()
FUNCTION
 implode() function: is PHP built-in functions that print the element in
the array list by converting the array into a string.
 implode() function takes two arguments: a string to use between each
element (the $glue), and the array to be joined together (the $pieces):
12
$my_array = [0, 1, 2];
echo implode(", " , $my_array);
This will output the
array in the following
format:
0, 1 , 2
To read more about built-in implode() function.
PRINTING THE ARRAY
ELEMENTS USING for LOOP
It possible to print the elements of array using for loop
Hint:
 always start the counter with 0 (why?)
 Always increase the loop by 1 (why?)
 Use count() function in the condition to identify the exact length of the array
13
$my_array = [0, 1, 2];
for( $i = 0; $i < count($my_array ); $i ++)
print( "Element $i is $my_array[$i] <br>" );
PRINTING THE ARRAY ELEMENTS
USING foreach LOOP
foreach loop works only on arrays, and is used to loop through each key/value
pair in an array.
Syntax:
14
$my_array = [0, 1, 2];
foreach( $my_array as $value)
print("$value <br> ");
foreach ($array as $value){
code to be executed;
}
ACCESSING, ADDING AND
CHANGING AN ELEMENT
 To access individual elements in an array use location index
 To add elements to the end of an array
15
$my_array = ["tic", "tac", "toe"];
echo $my_array[1];
$string_array=["element1","element2"];
$string_array[] = "element3";
echo implode(", ", $string_array);
tac
element1, element2, element3
outpu
t
outpu
t
ACCESSING, ADDING AND
CHANGING AN ELEMENT
 To change or reassign individual elements in an array use location
index
16
$string_array = ["element 1", "element 2", "element 3"];
$string_array[0] = "NEW! different first element";
echo $string_array[0];
echo implode(", ", $string_array);
NEW! different first element
outpu
t
outpu
t NEW! different first element, second element, third element
array_pop( ) function
 It removes the last element of an
array
 It has one argument only
 takes an array as its argument.
 it returns the removed element.
array_push( ) function
 It add elements to the end of an array
 It has two arguments
 first argument is the array.
 second argument are the elements to be
added to the end of the array
 it returns the new number of elements in
the array.
17
PUSHING AND POPPING
METHODS
$my_array = ["tic", "tac", "toe"];
array_pop($my_array);
// $my_array is now ["tic", "tac"]
$popped = array_pop($my_array);
// $popped is "tac "
// $my_array is now ["tic"]
$new_array = ["eeny"];
$num_added = array_push($new_array,
"meeny", "miny", "moe");
echo $num_added; // Prints: 4
echo implode(", ", $new_array);
// Prints: eeny, meeny, miny, moe
end
array_shift() function
 It removes the first element of an array
 It has one argument only
 takes an array as its argument.
 Each of the elements in the array will be
shifted down an index.
 it returns the removed element.
array_unshift() function
 It add elements to the beginning of an array
 It has two arguments:
 first argument is the array.
 second argument are the elements to be
added to the beginning of the array
 returns the new number of elements in the
array.
18
SHIFTING AND UNSHIFTING
METHODS
$adjectives=["bad", "good",
"great", "fantastic"];
$removed=array_shift($adjectives);
echo $removed; //Prints: bad
echo implode(", ", $adjectives);
// Prints: good, great, fantastic
$foods = ["pizza", "crackers", "apples",
"carrots"];
$arr_len = array_unshift($foods, "pasta",
"meatballs", "lettuce");
echo $arr_len; //Prints: 7
echo implode(", ", $foods);
/* Prints: pasta, meatballs, lettuce,
pizza, crackers, apples, carrots */
start
ARRAY TYPES
 There are three types of arrays in PHP, which are as follows:
19
•It use integer/numbers as their index number to identify each item of the array.
• Array element index start with 0, the next is 1, and so on.
1.Numeric Index Array (ordered array):
• Array inside another array
Nested Array:
• Arrays with nonnumeric index
Associative Array:
NESTED ARRAYS
We mentioned that arrays can hold elements of any type—this
even includes other arrays!
We can use chained operations to access and change elements
within a nested array
20
$nested_arr = [[2 , 4] , [3 , 9] , [4 , 16]];
$first_el = $nested_arr[0][0];
echo $first_el;
outpu
t 2
NESTED ARRAYS PRACTICE
21
Let’s breakdown the steps:
•We need the outermost array first: $very_nested[3] evaluates to the array ["cat", 6.1, [9,
"LOST!", 6], "mouse"]
•Next we need the array located at the 2nd location index: $very_nested[3][2] evaluates to the
array [9, "LOST!", 6]
•And finally, the element we’re looking for: $very_nested[3][2][1] evaluates to "LOST!"
$very_nested=[ 1 , "b“ , 33 , [ "cat", 6.1, [ 9 , "LOST!" , 6] , "mouse“ ] ,
7.1 ];
In the given array, change the element "LOST!" to "Found!".
$very_nested[3][2][1] = "Found!";
$very_nested=[ 1 , "b“ , 33 , [ "cat", 6.1, [ 9 , "Found!" , 6] , "mouse“ ]
, 7.1 ];
ARRAY TYPES
 There are three types of arrays in PHP, which are as follows:
22
•It use integer/numbers as their index number to identify each item of the array.
• Array element index start with 0, the next is 1, and so on.
1.Numeric Index Array (ordered array):
• Array inside another array
Nested Array:
• Arrays with nonnumeric index
Associative Array:
ASSOCIATIVE ARRAYS
 Associative arrays are collections of key=>value pairs.
 The key in an associative array must be either a string or an integer.
 The values held can be any type. We use the => operator to associate a key
with its value.
23
$my_array = ["panda" => "very cute", "lizard" =>
"cute", "cockroach" => "not very cute"];
$my_array['panda'] = "very cute";
$my_array['lizard'] = "cute";
$my_array['cockroach'] = "not very cute";
OR
ASSOCIATIVE ARRAYS
24
$about_me = array(
"fullname" => "Aseel Amjad",
"social" => 123456789
);
We can also build associative arrays using the PHP array() function.
To print Associative Arrays it is just like the numeric array
use print_r() or implode() function
PRINTING ASSOCIATIVE ARRAYS
USING for LOOP
 To do so many functions are needed:
1. reset function: sets the internal pointer to the first array element.
2. key function: returns the index of the element currently referenced by the
internal pointer.
3. next function: moves the internal pointer to the next element.
25
$about_me = array( "fullname" => "Aseel Amjad",
"social" => 123456789);
for(reset($about_me); $element= key($about_me);next($about_me))
print( "<p> $element is $about_me [$element] </p>" );
Could you
predict the
output?
PRINTING ASSOCIATIVE ARRAYS
USING foreach LOOP
 foreach loop statement, designed for iterating through arrays especially
associative arrays, because it does not assume that the array has
consecutive integer indices that start at 0.
26
$about_me = array( "fullname" => "Aseel Amjad",
"social" => 123456789);
foreach ($about_me as $element => $value )
print( "<p> $element is $value </p>" );
Could you
predict the
output?
JOINING ARRAYS (+)
27
PHP also lets us combine arrays. The union (+) operator takes two array
operands and returns a new array with any unique keys from the second array
appended to the first array.
$my_array = ["panda" => "very cute", "lizard" => "cute",
"cockroach" => "not very cute"];
$more_rankings = ["capybara" => "cutest", "lizard" => "not
cute", "dog" => "max cuteness"];
$animal_rankings = $my_array + $more_rankings;
implode(", ", $animal_rankings)
since "lizard" is not a unique key, $animal_rankings["lizard"] will
retain the value of $my_array["lizard"] (which is "cute").
union (+)
operator
wouldn’t
work with
numerical
(ordered)
array …
why?
very cute, cute, not very cute, cutest, max cuteness
outpu
t
QUESTION
 What does the following code return?
$arr = array(1,3,5);
$count = count($arr);
if ($count == 0)
echo "An array is empty.";
else
echo "An array has $count elements.";
28
REVIEW
29
•In PHP, we refer to this data structure as ordered arrays.
•The location of an element in an array is known as its index.
•The elements in an ordered array are arranged in ascending numerical order
starting with index zero.
•We can construct ordered arrays with a built-in PHP function: array().
•We can construct ordered arrays with short array syntax, e.g. [1,2,3].
•We can print arrays using the built-in print_r() function or by converting them
into strings using the implode() function.
•We use square brackets ([]) to access elements in an array by their index.
•We can add elements to the end of an array by appending square brackets ([])
to an array variable name and assigning the value with the assignment operator
(=).
•We can change elements in an array using array indexing and the assignment
operator.
REVIEW
30
 The array_pop() function removes the last element of an array.
 The array_push() function adds elements to the end of an array.
 The array_shift() function removes the first element of an array.
 The array_unshift() function adds elements to the beginning of the array.
 We can use chained square brackets ([]) to access and change elements within a nested
array.
 Associative arrays are data structures in which string or integer keys are associated with
values.
 We use the => operator to associate a key with its value. $my_array = ["panda"=>"very cute"]
 To print an array’s keys and their values, we can use the print_r() function.
 We access the value associated with a given key by using square brackets ([ ]).
 We can assign values to keys using this same indexing syntax and the assignment operator (=):
$my_array["dog"] = "good cuteness";
 This same syntax can be used to change existing elements. $my_array["dog"] = "max
cuteness";
 In PHP, associative arrays and ordered arrays are different uses of the same data type.
 The union (+) operator takes two array operands and returns a new array with any unique keys
from the second array appended to the first array.
USEFUL
VIDEOS
SOURCE
ABOUT ARRAY
 45: What are arrays used for in PHP - PHP tutorial
 46: Insert data into array in PHP - PHP tutorial
 48: Different types of array in PHP - PHP tutorial
 49: What are associative arrays in PHP - PHP
tutorial
 50: What are multidimensional arrays in PHP - PHP
tutorial
Please refer for the given videos
links if needed
31

More Related Content

PPTX
PHP array 1
Mudasir Syed
 
PPTX
5 Arry in PHP.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
ayushmishraaa09
 
PPT
PHP - Introduction to PHP Arrays
Vibrant Technologies & Computers
 
PPTX
Unit 2-Arrays.pptx
mythili213835
 
PPT
PHP array 2
Mudasir Syed
 
PPTX
Chapter 2 wbp.pptx
40NehaPagariya
 
PPT
Arrays in php
Laiby Thomas
 
PPT
Web Technology - PHP Arrays
Tarang Desai
 
PHP array 1
Mudasir Syed
 
5 Arry in PHP.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
ayushmishraaa09
 
PHP - Introduction to PHP Arrays
Vibrant Technologies & Computers
 
Unit 2-Arrays.pptx
mythili213835
 
PHP array 2
Mudasir Syed
 
Chapter 2 wbp.pptx
40NehaPagariya
 
Arrays in php
Laiby Thomas
 
Web Technology - PHP Arrays
Tarang Desai
 

Similar to Lecture 5 array in PHP.pptxLecture 10 CSS part 2.pptxvvvvvvvvvvvvvv (20)

PDF
Array String - Web Programming
Amirul Azhar
 
PPT
PHP-04-Arrays.ppt
Leandro660423
 
PDF
4.1 PHP Arrays
Jalpesh Vasa
 
PPTX
Chap 3php array part1
monikadeshmane
 
PPTX
Arrays in PHP
davidahaskins
 
PPTX
PHP Arrays_Introduction
To Sum It Up
 
PPTX
UNIT IV (4).pptx
DrDhivyaaCRAssistant
 
PPTX
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Dhivyaa C.R
 
PPTX
Php arrays
1crazyguy
 
PPSX
DIWE - Advanced PHP Concepts
Rasan Samarasinghe
 
PPT
Class 4 - PHP Arrays
Ahmed Swilam
 
PPTX
Arrays syntax and it's functions in php.pptx
NikhilVij6
 
PDF
Php array
Nikul Shah
 
PPT
Using arrays with PHP for forms and storing information
Nicole Ryan
 
PPT
Arrays in PHP
Compare Infobase Limited
 
PPTX
Working with arrays in php
Kamal Acharya
 
PPT
PHP and MySQL with snapshots
richambra
 
PPT
Php Using Arrays
mussawir20
 
PPT
Php Chapter 2 3 Training
Chris Chubb
 
DOCX
Array andfunction
Girmachew Tilahun
 
Array String - Web Programming
Amirul Azhar
 
PHP-04-Arrays.ppt
Leandro660423
 
4.1 PHP Arrays
Jalpesh Vasa
 
Chap 3php array part1
monikadeshmane
 
Arrays in PHP
davidahaskins
 
PHP Arrays_Introduction
To Sum It Up
 
UNIT IV (4).pptx
DrDhivyaaCRAssistant
 
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Dhivyaa C.R
 
Php arrays
1crazyguy
 
DIWE - Advanced PHP Concepts
Rasan Samarasinghe
 
Class 4 - PHP Arrays
Ahmed Swilam
 
Arrays syntax and it's functions in php.pptx
NikhilVij6
 
Php array
Nikul Shah
 
Using arrays with PHP for forms and storing information
Nicole Ryan
 
Working with arrays in php
Kamal Acharya
 
PHP and MySQL with snapshots
richambra
 
Php Using Arrays
mussawir20
 
Php Chapter 2 3 Training
Chris Chubb
 
Array andfunction
Girmachew Tilahun
 
Ad

More from ZahouAmel1 (18)

PPTX
2- lec_2.pptxDesigning with Type, SpacingDesigning with Type, SpacingDesignin...
ZahouAmel1
 
PPTX
1-Lect_1.pptxLecture 5 array in PHP.pptx
ZahouAmel1
 
PPTX
Lecture 8 PHP and MYSQL part 2.ppType Classificationtx
ZahouAmel1
 
PPTX
Lecture 9 CSS part 1.pptxType Classification
ZahouAmel1
 
PPTX
Lecture 2 HTML part 1.pptxLecture 10 CSS part 2.pptxvvvvvvvvvvvvvv
ZahouAmel1
 
PPTX
Lecture 10 CSS part 2.pptxvvvvvvvvvvvvvv
ZahouAmel1
 
PPTX
Lec 1 Introduction to Computer and Information Technology #1.pptx
ZahouAmel1
 
PPTX
DB-Lec1.pptxUpdatedpython.pptxUpdatedpython.pptx
ZahouAmel1
 
PPTX
DB- lec2.pptxUpdatedpython.pptxUpdatedpy
ZahouAmel1
 
PPTX
Updatedpython.pptxUpdatedpython.pptxUpdatedpython.pptx
ZahouAmel1
 
PPTX
4-Lect_4-2.pptx4-Lect_4-2.pptx4-Lect_4-2.pptx
ZahouAmel1
 
PPTX
5-LEC- 5.pptxTransport Layer. Transport Layer Protocols
ZahouAmel1
 
PPTX
6-LEC- 6.pptx Network Layer. Addressing Subnetting Mask (default and subnet) ...
ZahouAmel1
 
PPTX
7-Lect_7 .pptxNetwork Layer. Addressing Subnetting Mask (default and subnet) ...
ZahouAmel1
 
PPTX
7-Lect_7 .pptxNetwork LayerNetwork Layer
ZahouAmel1
 
PPTX
8-Lect_8 Addressing the Network.tcp.pptx
ZahouAmel1
 
PPTX
9-Lect_9-1.pptx9-Lect_9-1.pptx9-Lect_9-1.pptx
ZahouAmel1
 
PPTX
9-Lect_9-2.pptx DataLink Layer DataLink Layer
ZahouAmel1
 
2- lec_2.pptxDesigning with Type, SpacingDesigning with Type, SpacingDesignin...
ZahouAmel1
 
1-Lect_1.pptxLecture 5 array in PHP.pptx
ZahouAmel1
 
Lecture 8 PHP and MYSQL part 2.ppType Classificationtx
ZahouAmel1
 
Lecture 9 CSS part 1.pptxType Classification
ZahouAmel1
 
Lecture 2 HTML part 1.pptxLecture 10 CSS part 2.pptxvvvvvvvvvvvvvv
ZahouAmel1
 
Lecture 10 CSS part 2.pptxvvvvvvvvvvvvvv
ZahouAmel1
 
Lec 1 Introduction to Computer and Information Technology #1.pptx
ZahouAmel1
 
DB-Lec1.pptxUpdatedpython.pptxUpdatedpython.pptx
ZahouAmel1
 
DB- lec2.pptxUpdatedpython.pptxUpdatedpy
ZahouAmel1
 
Updatedpython.pptxUpdatedpython.pptxUpdatedpython.pptx
ZahouAmel1
 
4-Lect_4-2.pptx4-Lect_4-2.pptx4-Lect_4-2.pptx
ZahouAmel1
 
5-LEC- 5.pptxTransport Layer. Transport Layer Protocols
ZahouAmel1
 
6-LEC- 6.pptx Network Layer. Addressing Subnetting Mask (default and subnet) ...
ZahouAmel1
 
7-Lect_7 .pptxNetwork Layer. Addressing Subnetting Mask (default and subnet) ...
ZahouAmel1
 
7-Lect_7 .pptxNetwork LayerNetwork Layer
ZahouAmel1
 
8-Lect_8 Addressing the Network.tcp.pptx
ZahouAmel1
 
9-Lect_9-1.pptx9-Lect_9-1.pptx9-Lect_9-1.pptx
ZahouAmel1
 
9-Lect_9-2.pptx DataLink Layer DataLink Layer
ZahouAmel1
 
Ad

Recently uploaded (20)

PDF
Arihant Class 10 All in One Maths full pdf
sajal kumar
 
PDF
3.The-Rise-of-the-Marathas.pdfppt/pdf/8th class social science Exploring Soci...
Sandeep Swamy
 
PPTX
Strengthening open access through collaboration: building connections with OP...
Jisc
 
PDF
Sunset Boulevard Student Revision Booklet
jpinnuck
 
PDF
Module 3: Health Systems Tutorial Slides S2 2025
Jonathan Hallett
 
PDF
High Ground Student Revision Booklet Preview
jpinnuck
 
DOCX
Action Plan_ARAL PROGRAM_ STAND ALONE SHS.docx
Levenmartlacuna1
 
PPTX
Open Quiz Monsoon Mind Game Prelims.pptx
Sourav Kr Podder
 
PPTX
PPTs-The Rise of Empiresghhhhhhhh (1).pptx
academysrusti114
 
PPTX
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PoojaSen20
 
PPTX
Skill Development Program For Physiotherapy Students by SRY.pptx
Prof.Dr.Y.SHANTHOSHRAJA MPT Orthopedic., MSc Microbiology
 
PDF
Review of Related Literature & Studies.pdf
Thelma Villaflores
 
PPTX
Presentation on Janskhiya sthirata kosh.
Ms Usha Vadhel
 
PPTX
Care of patients with elImination deviation.pptx
AneetaSharma15
 
PPT
Python Programming Unit II Control Statements.ppt
CUO VEERANAN VEERANAN
 
PPTX
Odoo 18 Sales_ Managing Quotation Validity
Celine George
 
DOCX
SAROCES Action-Plan FOR ARAL PROGRAM IN DEPED
Levenmartlacuna1
 
PDF
Electricity-Magnetic-and-Heating-Effects 4th Chapter/8th-science-curiosity.pd...
Sandeep Swamy
 
PPTX
Congenital Hypothyroidism pptx
AneetaSharma15
 
PPTX
An introduction to Prepositions for beginners.pptx
drsiddhantnagine
 
Arihant Class 10 All in One Maths full pdf
sajal kumar
 
3.The-Rise-of-the-Marathas.pdfppt/pdf/8th class social science Exploring Soci...
Sandeep Swamy
 
Strengthening open access through collaboration: building connections with OP...
Jisc
 
Sunset Boulevard Student Revision Booklet
jpinnuck
 
Module 3: Health Systems Tutorial Slides S2 2025
Jonathan Hallett
 
High Ground Student Revision Booklet Preview
jpinnuck
 
Action Plan_ARAL PROGRAM_ STAND ALONE SHS.docx
Levenmartlacuna1
 
Open Quiz Monsoon Mind Game Prelims.pptx
Sourav Kr Podder
 
PPTs-The Rise of Empiresghhhhhhhh (1).pptx
academysrusti114
 
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PoojaSen20
 
Skill Development Program For Physiotherapy Students by SRY.pptx
Prof.Dr.Y.SHANTHOSHRAJA MPT Orthopedic., MSc Microbiology
 
Review of Related Literature & Studies.pdf
Thelma Villaflores
 
Presentation on Janskhiya sthirata kosh.
Ms Usha Vadhel
 
Care of patients with elImination deviation.pptx
AneetaSharma15
 
Python Programming Unit II Control Statements.ppt
CUO VEERANAN VEERANAN
 
Odoo 18 Sales_ Managing Quotation Validity
Celine George
 
SAROCES Action-Plan FOR ARAL PROGRAM IN DEPED
Levenmartlacuna1
 
Electricity-Magnetic-and-Heating-Effects 4th Chapter/8th-science-curiosity.pd...
Sandeep Swamy
 
Congenital Hypothyroidism pptx
AneetaSharma15
 
An introduction to Prepositions for beginners.pptx
drsiddhantnagine
 

Lecture 5 array in PHP.pptxLecture 10 CSS part 2.pptxvvvvvvvvvvvvvv

  • 1. Chapter 19-2 PHP LECTUR 5: ARRAYS IN PHP CHAPTER 19 Web-Based Design IT210 1
  • 2. OBJECTIVES By the end of this lecture student will be able to:  Understanding array concept.  Creating arrays  Understanding the difference types of array  Dealing with arrays by printing ,adding , deleting ,changing elements from array 2
  • 3. OUTL INE 3 Arrays in PHP. Types of Array. Initializing and Manipulating Arrays.
  • 4. ARRAYS IN PHP  An array is a group of data type which is used to store multiple values in a single variable.  Array names: like other variables, begin with the $ symbol.  Individual array elements are accessed by following the array’s variable name with an index enclosed in square brackets ([]).  Array index: The location of an element in an array is known as its index. The elements in an ordered array are arranged in ascending numerical order starting with zero—the index of the first array element is 0, the index of the second is 1, and so on. 4
  • 5. ARRAYS IN PHP From the picture:  What is the array name?  How many element does it contain ?  What is the index of "Fish" element ? 5 $my_array= [7, "24" , "Fish", "hat stand"]
  • 6. ARRAY TYPES  There are three types of arrays in PHP, which are as follows: 6 •It use integer/numbers as their index number to identify each item of the array. • Array element index start with 0, the next is 1, and so on. 1.Numeric Index Array (ordered array): • Array inside another array Nested Array: • Arrays with nonnumeric index Associative Array:
  • 7. CREATING ARRAYS IN PHP There are two ways to create an array in PHP: 1. Creating Arrays with array() function e.g: $my_array = array(0, 1, 2); 2. Creating Arrays with Short Syntax e.g: $my_array = [0, 1, 2]; 7
  • 8. CREATING ARRAYS WITH array() FUNCTION  Constructing ordered arrays with a built-in PHP function: array().  The array() function returns an array.  Each of the arguments with which the function was invoked becomes an element in the array (in the order they were passed in). 8 $my_array = array(0, 1, 2); $string_array = array("first element", "second element"); $mixed_array = array(1, "chicken", 78.2, "bubbles are crazy!"); To read more about built-in PHP function: array().
  • 9. CREATING ARRAYS WITH SHORT SYNTAX  Creating an array is also possible by wrapping comma-separated elements in square brackets ([ ]). 9 $my_array = [0, 1, 2]; $string_array = ["first element", " second element "]; $mixed_array = [1, "chicken", 78.2, "bubbles are crazy! "];
  • 10. count() FUNCTION  Function count returns the total number of elements in the array. 10 $my_array = [0, 1, 2]; $string_array = ["first element", " second element "]; $mixed_array = [1, "chicken", 78.2, "bubbles are crazy! "]; echo count($my_array); echo count($string_array); echo count($mixed_array); To read more built-in PHP count() function output 3 output 2 output 4
  • 11. PRINTING ARRAYS WITH print_r() FUNCTION  Since arrays are a more complicated data type than strings or integers, using echo won’t have the desired result: 11 $my_array = [0, 1, 2]; echo $my_array; print_r() function: is PHP built-in functions that print the contents of the array $my_array = [0, 1, 2]; print_r($my_array); Echo “<br>”; This will output the array in the following format: Array ( [0 ]=> 0 [1] => 1 [2] => 2 ) To read more about built-in print_r() function This will output the array: array
  • 12. PRINTING ARRAYS WITH implode() FUNCTION  implode() function: is PHP built-in functions that print the element in the array list by converting the array into a string.  implode() function takes two arguments: a string to use between each element (the $glue), and the array to be joined together (the $pieces): 12 $my_array = [0, 1, 2]; echo implode(", " , $my_array); This will output the array in the following format: 0, 1 , 2 To read more about built-in implode() function.
  • 13. PRINTING THE ARRAY ELEMENTS USING for LOOP It possible to print the elements of array using for loop Hint:  always start the counter with 0 (why?)  Always increase the loop by 1 (why?)  Use count() function in the condition to identify the exact length of the array 13 $my_array = [0, 1, 2]; for( $i = 0; $i < count($my_array ); $i ++) print( "Element $i is $my_array[$i] <br>" );
  • 14. PRINTING THE ARRAY ELEMENTS USING foreach LOOP foreach loop works only on arrays, and is used to loop through each key/value pair in an array. Syntax: 14 $my_array = [0, 1, 2]; foreach( $my_array as $value) print("$value <br> "); foreach ($array as $value){ code to be executed; }
  • 15. ACCESSING, ADDING AND CHANGING AN ELEMENT  To access individual elements in an array use location index  To add elements to the end of an array 15 $my_array = ["tic", "tac", "toe"]; echo $my_array[1]; $string_array=["element1","element2"]; $string_array[] = "element3"; echo implode(", ", $string_array); tac element1, element2, element3 outpu t outpu t
  • 16. ACCESSING, ADDING AND CHANGING AN ELEMENT  To change or reassign individual elements in an array use location index 16 $string_array = ["element 1", "element 2", "element 3"]; $string_array[0] = "NEW! different first element"; echo $string_array[0]; echo implode(", ", $string_array); NEW! different first element outpu t outpu t NEW! different first element, second element, third element
  • 17. array_pop( ) function  It removes the last element of an array  It has one argument only  takes an array as its argument.  it returns the removed element. array_push( ) function  It add elements to the end of an array  It has two arguments  first argument is the array.  second argument are the elements to be added to the end of the array  it returns the new number of elements in the array. 17 PUSHING AND POPPING METHODS $my_array = ["tic", "tac", "toe"]; array_pop($my_array); // $my_array is now ["tic", "tac"] $popped = array_pop($my_array); // $popped is "tac " // $my_array is now ["tic"] $new_array = ["eeny"]; $num_added = array_push($new_array, "meeny", "miny", "moe"); echo $num_added; // Prints: 4 echo implode(", ", $new_array); // Prints: eeny, meeny, miny, moe end
  • 18. array_shift() function  It removes the first element of an array  It has one argument only  takes an array as its argument.  Each of the elements in the array will be shifted down an index.  it returns the removed element. array_unshift() function  It add elements to the beginning of an array  It has two arguments:  first argument is the array.  second argument are the elements to be added to the beginning of the array  returns the new number of elements in the array. 18 SHIFTING AND UNSHIFTING METHODS $adjectives=["bad", "good", "great", "fantastic"]; $removed=array_shift($adjectives); echo $removed; //Prints: bad echo implode(", ", $adjectives); // Prints: good, great, fantastic $foods = ["pizza", "crackers", "apples", "carrots"]; $arr_len = array_unshift($foods, "pasta", "meatballs", "lettuce"); echo $arr_len; //Prints: 7 echo implode(", ", $foods); /* Prints: pasta, meatballs, lettuce, pizza, crackers, apples, carrots */ start
  • 19. ARRAY TYPES  There are three types of arrays in PHP, which are as follows: 19 •It use integer/numbers as their index number to identify each item of the array. • Array element index start with 0, the next is 1, and so on. 1.Numeric Index Array (ordered array): • Array inside another array Nested Array: • Arrays with nonnumeric index Associative Array:
  • 20. NESTED ARRAYS We mentioned that arrays can hold elements of any type—this even includes other arrays! We can use chained operations to access and change elements within a nested array 20 $nested_arr = [[2 , 4] , [3 , 9] , [4 , 16]]; $first_el = $nested_arr[0][0]; echo $first_el; outpu t 2
  • 21. NESTED ARRAYS PRACTICE 21 Let’s breakdown the steps: •We need the outermost array first: $very_nested[3] evaluates to the array ["cat", 6.1, [9, "LOST!", 6], "mouse"] •Next we need the array located at the 2nd location index: $very_nested[3][2] evaluates to the array [9, "LOST!", 6] •And finally, the element we’re looking for: $very_nested[3][2][1] evaluates to "LOST!" $very_nested=[ 1 , "b“ , 33 , [ "cat", 6.1, [ 9 , "LOST!" , 6] , "mouse“ ] , 7.1 ]; In the given array, change the element "LOST!" to "Found!". $very_nested[3][2][1] = "Found!"; $very_nested=[ 1 , "b“ , 33 , [ "cat", 6.1, [ 9 , "Found!" , 6] , "mouse“ ] , 7.1 ];
  • 22. ARRAY TYPES  There are three types of arrays in PHP, which are as follows: 22 •It use integer/numbers as their index number to identify each item of the array. • Array element index start with 0, the next is 1, and so on. 1.Numeric Index Array (ordered array): • Array inside another array Nested Array: • Arrays with nonnumeric index Associative Array:
  • 23. ASSOCIATIVE ARRAYS  Associative arrays are collections of key=>value pairs.  The key in an associative array must be either a string or an integer.  The values held can be any type. We use the => operator to associate a key with its value. 23 $my_array = ["panda" => "very cute", "lizard" => "cute", "cockroach" => "not very cute"]; $my_array['panda'] = "very cute"; $my_array['lizard'] = "cute"; $my_array['cockroach'] = "not very cute"; OR
  • 24. ASSOCIATIVE ARRAYS 24 $about_me = array( "fullname" => "Aseel Amjad", "social" => 123456789 ); We can also build associative arrays using the PHP array() function. To print Associative Arrays it is just like the numeric array use print_r() or implode() function
  • 25. PRINTING ASSOCIATIVE ARRAYS USING for LOOP  To do so many functions are needed: 1. reset function: sets the internal pointer to the first array element. 2. key function: returns the index of the element currently referenced by the internal pointer. 3. next function: moves the internal pointer to the next element. 25 $about_me = array( "fullname" => "Aseel Amjad", "social" => 123456789); for(reset($about_me); $element= key($about_me);next($about_me)) print( "<p> $element is $about_me [$element] </p>" ); Could you predict the output?
  • 26. PRINTING ASSOCIATIVE ARRAYS USING foreach LOOP  foreach loop statement, designed for iterating through arrays especially associative arrays, because it does not assume that the array has consecutive integer indices that start at 0. 26 $about_me = array( "fullname" => "Aseel Amjad", "social" => 123456789); foreach ($about_me as $element => $value ) print( "<p> $element is $value </p>" ); Could you predict the output?
  • 27. JOINING ARRAYS (+) 27 PHP also lets us combine arrays. The union (+) operator takes two array operands and returns a new array with any unique keys from the second array appended to the first array. $my_array = ["panda" => "very cute", "lizard" => "cute", "cockroach" => "not very cute"]; $more_rankings = ["capybara" => "cutest", "lizard" => "not cute", "dog" => "max cuteness"]; $animal_rankings = $my_array + $more_rankings; implode(", ", $animal_rankings) since "lizard" is not a unique key, $animal_rankings["lizard"] will retain the value of $my_array["lizard"] (which is "cute"). union (+) operator wouldn’t work with numerical (ordered) array … why? very cute, cute, not very cute, cutest, max cuteness outpu t
  • 28. QUESTION  What does the following code return? $arr = array(1,3,5); $count = count($arr); if ($count == 0) echo "An array is empty."; else echo "An array has $count elements."; 28
  • 29. REVIEW 29 •In PHP, we refer to this data structure as ordered arrays. •The location of an element in an array is known as its index. •The elements in an ordered array are arranged in ascending numerical order starting with index zero. •We can construct ordered arrays with a built-in PHP function: array(). •We can construct ordered arrays with short array syntax, e.g. [1,2,3]. •We can print arrays using the built-in print_r() function or by converting them into strings using the implode() function. •We use square brackets ([]) to access elements in an array by their index. •We can add elements to the end of an array by appending square brackets ([]) to an array variable name and assigning the value with the assignment operator (=). •We can change elements in an array using array indexing and the assignment operator.
  • 30. REVIEW 30  The array_pop() function removes the last element of an array.  The array_push() function adds elements to the end of an array.  The array_shift() function removes the first element of an array.  The array_unshift() function adds elements to the beginning of the array.  We can use chained square brackets ([]) to access and change elements within a nested array.  Associative arrays are data structures in which string or integer keys are associated with values.  We use the => operator to associate a key with its value. $my_array = ["panda"=>"very cute"]  To print an array’s keys and their values, we can use the print_r() function.  We access the value associated with a given key by using square brackets ([ ]).  We can assign values to keys using this same indexing syntax and the assignment operator (=): $my_array["dog"] = "good cuteness";  This same syntax can be used to change existing elements. $my_array["dog"] = "max cuteness";  In PHP, associative arrays and ordered arrays are different uses of the same data type.  The union (+) operator takes two array operands and returns a new array with any unique keys from the second array appended to the first array.
  • 31. USEFUL VIDEOS SOURCE ABOUT ARRAY  45: What are arrays used for in PHP - PHP tutorial  46: Insert data into array in PHP - PHP tutorial  48: Different types of array in PHP - PHP tutorial  49: What are associative arrays in PHP - PHP tutorial  50: What are multidimensional arrays in PHP - PHP tutorial Please refer for the given videos links if needed 31