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
Ad

More Related Content

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

UNIT IV (4).pptx
UNIT IV (4).pptxUNIT IV (4).pptx
UNIT IV (4).pptx
DrDhivyaaCRAssistant
 
Array properties
Array propertiesArray properties
Array properties
Shravan Sharma
 
object oriented programing in python and pip
object oriented programing in python and pipobject oriented programing in python and pip
object oriented programing in python and pip
LakshmiMarineni
 
Array assignment
Array assignmentArray assignment
Array assignment
Ahmad Kamal
 
C++ arrays part1
C++ arrays part1C++ arrays part1
C++ arrays part1
Subhasis Nayak
 
DSA UNIT II ARRAY AND LIST - notes
DSA UNIT II ARRAY AND LIST - notesDSA UNIT II ARRAY AND LIST - notes
DSA UNIT II ARRAY AND LIST - notes
swathirajstar
 
Chapter 7.1
Chapter 7.1Chapter 7.1
Chapter 7.1
sotlsoc
 
9780538745840 ppt ch06
9780538745840 ppt ch069780538745840 ppt ch06
9780538745840 ppt ch06
Terry Yoast
 
Data structures and algorithms arrays
Data structures and algorithms   arraysData structures and algorithms   arrays
Data structures and algorithms arrays
chauhankapil
 
Using arrays with PHP for forms and storing information
Using arrays with PHP for forms and storing informationUsing arrays with PHP for forms and storing information
Using arrays with PHP for forms and storing information
Nicole Ryan
 
Array In C++ programming object oriented programming
Array In C++ programming object oriented programmingArray In C++ programming object oriented programming
Array In C++ programming object oriented programming
Ahmad177077
 
Homework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfHomework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdf
aroraopticals15
 
Arrays
ArraysArrays
Arrays
Edwin Llamas
 
Arrays
ArraysArrays
Arrays
ViniVini48
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
moazamali28
 
Data structures arrays
Data structures   arraysData structures   arrays
Data structures arrays
maamir farooq
 
Arrays Basicfundamentaldatastructure.ppt
Arrays Basicfundamentaldatastructure.pptArrays Basicfundamentaldatastructure.ppt
Arrays Basicfundamentaldatastructure.ppt
JyothiAmpally
 
Java arrays (1)
Java arrays (1)Java arrays (1)
Java arrays (1)
Liza Abello
 
Python array
Python arrayPython array
Python array
Arnab Chakraborty
 
Chyuuuuuuuuuuryyyyyyyyyyy123456789786341.pptx
Chyuuuuuuuuuuryyyyyyyyyyy123456789786341.pptxChyuuuuuuuuuuryyyyyyyyyyy123456789786341.pptx
Chyuuuuuuuuuuryyyyyyyyyyy123456789786341.pptx
RobertCarreonBula
 
object oriented programing in python and pip
object oriented programing in python and pipobject oriented programing in python and pip
object oriented programing in python and pip
LakshmiMarineni
 
Array assignment
Array assignmentArray assignment
Array assignment
Ahmad Kamal
 
DSA UNIT II ARRAY AND LIST - notes
DSA UNIT II ARRAY AND LIST - notesDSA UNIT II ARRAY AND LIST - notes
DSA UNIT II ARRAY AND LIST - notes
swathirajstar
 
Chapter 7.1
Chapter 7.1Chapter 7.1
Chapter 7.1
sotlsoc
 
9780538745840 ppt ch06
9780538745840 ppt ch069780538745840 ppt ch06
9780538745840 ppt ch06
Terry Yoast
 
Data structures and algorithms arrays
Data structures and algorithms   arraysData structures and algorithms   arrays
Data structures and algorithms arrays
chauhankapil
 
Using arrays with PHP for forms and storing information
Using arrays with PHP for forms and storing informationUsing arrays with PHP for forms and storing information
Using arrays with PHP for forms and storing information
Nicole Ryan
 
Array In C++ programming object oriented programming
Array In C++ programming object oriented programmingArray In C++ programming object oriented programming
Array In C++ programming object oriented programming
Ahmad177077
 
Homework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfHomework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdf
aroraopticals15
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
moazamali28
 
Data structures arrays
Data structures   arraysData structures   arrays
Data structures arrays
maamir farooq
 
Arrays Basicfundamentaldatastructure.ppt
Arrays Basicfundamentaldatastructure.pptArrays Basicfundamentaldatastructure.ppt
Arrays Basicfundamentaldatastructure.ppt
JyothiAmpally
 
Chyuuuuuuuuuuryyyyyyyyyyy123456789786341.pptx
Chyuuuuuuuuuuryyyyyyyyyyy123456789786341.pptxChyuuuuuuuuuuryyyyyyyyyyy123456789786341.pptx
Chyuuuuuuuuuuryyyyyyyyyyy123456789786341.pptx
RobertCarreonBula
 

More from ZahouAmel1 (18)

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

Recently uploaded (20)

CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdfBiophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
PKLI-Institute of Nursing and Allied Health Sciences Lahore , Pakistan.
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 AccountingHow to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
Celine George
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
Handling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptxHandling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptx
AuthorAIDNationalRes
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
Operations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdfOperations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdf
Arab Academy for Science, Technology and Maritime Transport
 
New Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptxNew Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptx
milanasargsyan5
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
Social Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy StudentsSocial Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy Students
DrNidhiAgarwal
 
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 AccountingHow to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
Celine George
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
Handling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptxHandling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptx
AuthorAIDNationalRes
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
New Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptxNew Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptx
milanasargsyan5
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
Social Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy StudentsSocial Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy Students
DrNidhiAgarwal
 
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 
Ad

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