0% found this document useful (0 votes)
5 views28 pages

Lecture 5 - Arrays

This document covers the use of arrays in PHP, detailing their definition, types (indexed and associative), and methods for creating, printing, and manipulating arrays. It includes examples of predefined arrays, array functions, and techniques for iterating through both standard and multidimensional arrays. The document also provides references for further reading on PHP arrays.

Uploaded by

Pele Mpele
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views28 pages

Lecture 5 - Arrays

This document covers the use of arrays in PHP, detailing their definition, types (indexed and associative), and methods for creating, printing, and manipulating arrays. It includes examples of predefined arrays, array functions, and techniques for iterating through both standard and multidimensional arrays. The document also provides references for further reading on PHP arrays.

Uploaded by

Pele Mpele
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 28

DYNAMIC WEB DEVELOPMENT

WEEK 5.A: ARRAYS


Correspond to Ch 2

Dr. Basel Almourad


GOALS
 Learn about how are arrays used in PHP

OUTLINE
1. Definition
2. Predefined arrays
3. Array declaration
4. Array printing
5. Multidimensional arrays
6. Q & A
ARRAYS
 Hold multiple values
 Structured as a series of key-value pairs

 PHP supports two kinds of arrays:


 indexed  e.g. $students[2]
 associative  e.g. $students[‘M0256’]

To refer to a specific value in an array, start with the


array variable name, followed by the key within
square brackets:
e.g. $students[2], $students[‘M0256’]
ARRAYS
 Other examples

No quotations (it is a number)

- $artists[0];  returns The


Mynabirds

- $states['MD’]  returns
Maryland

Quotations (it is a string)


ARRAYS
 Some PHP Predefined Arrays
$_SERVER
$_REQUEST
$_GET
$_POST

 Others
 $_ENV
 $_SESSION
 $_COOKIE

 These are called the superglobal variables


ARRAYS
 In previous lecture, we used $_REQUEST to validate a form
 One important recommendation: be precise when referring
to variables
 Use $_POST instead of $_REQUEST (data submitted using POST)

handle_form (lecture4).php
<?php
$name = $_REQUEST['name'];
$age = $_REQUEST['age'];
$gender=$_REQUEST['gender'];
….. handle_form (lecture5).php
?> <?php
$name = $_POST['name'];
$age = $_POST ['age'];
$gender=$_POST ['gender'];
…..
?>
ARRAYS
 Creating arrays:
A. Add an element at a time :
$band[ ] = 'Jemaine';
$band[ ] = 'Bret'; ! $and[0] will be Jemaine, etc.
$band[ ] = 'Murray’;

B. specify the key when adding an element


$band['fan'] = 'Mel';
$band['fan'] = 'Dave'; // New value
$fruit[2] = 'apple';
$fruit[2] = 'orange'; // New value

! If a key already exist, its value will be overwritten !


ARRAYS
 Creating arrays <?php
$fruits=array('Apples','Bananas','D
C. Use array() function ates','Oranges');
/* this is the same as $fruits*/
$states = array ( $fruits_2[0]='Apples';
‘AD' => ‘Abu Dhabi', $fruits_2[1]='Bananas';
‘DX' => ‘Dubai’ $fruits_2[2]='Dates';
$fruits_2[3]='Oranges';
);
/* this is the same as $fruits as
Can also work without specifying the key well*/
$fruits_3[]='Apples';
$fruits_3[]='Bananas';
$artists = array ('Clem Snide’, 'Shins', 'Eels'); $fruits_3[]='Dates';
$fruits_3[]='Oranges';
?>
Index Value
0 ‘Apples’
1 ‘Bananas’
2 ‘Dates’
3 ‘Oranges’
ARRAYS
 Creating arrays
D. Use array() function
 If first numeric key value is set, , the added values will be keyed
incrementally

$days = array (1 => 'Sun', 'Mon’, 'Tue’);


 echo $days[3]; // returns Tue

$six $let
E. Use range function
 Creates an array of sequential numbers or letters

$six = range (1, 6);


$let = range (‘a’, ‘f’);
PRINTING ARRAYS
 Printing Arrays
echo “List of students: $students”  will not work

List of students: Array

 Need to print the individual items

echo “The second student: $students[1]”  will print 2nd student


echo “List of students: $students [‘M0256’]”  will not work
o Use: echo “Student with ID M0256: {$students [‘M0256’]}”
PRINTING ARRAYS
 print_r()
Can be used for printing array content for testing
 $fruits=array('Apples','Bananas','Dates','Oranges’);
 Print_r($fruits);

arrays_1.php
ADDING ELEMENTS INTO
AN ARRAY
You can add a new item into an array by simply using this syntax:

$array_name[]=‘value’;

This statement will simply append that item to the end of the array.

You can add a new entry (key, value) to an associative arrays using this
syntax:

$associative_array_name[‘Key’]=‘value’;

If the key exists, it will simply update the value for the entry. Otherwise, it will
add a new entry.
ADDING ELEMENTS INTO
AN ARRAY
<?php

$fruits=array('Apples','Bananas','Dates','Oranges');

$fruits_2=array('red'=>'Apples','yellow'=>'Bananas',
'beige'=>'Cantaloupes','brown'=>'Dates');

$fruits[]='Kiwi'; //add Kiwi to the end of $fruits


//array_push($fruits, ‘Kiwi’); a different way

$fruits_2['lightbrown']='Kiwi'; //add the entry ‘lightbrown: Kiwi’


?>

adding_items_to_array.php
DELETING ELEMENTS
FROM AN ARRAY
 You can use unset to delete an item from an array.
 Once you delete the item, the item will seize to exist, and the
size of the array will shrink by 1.

<?php

$fruits=array('Apples','Bananas','Dates','Oranges');

$fruits_2=array('red'=>'Apples','yellow'=>'Bananas',
'beige'=>'Cantaloupes','brown'=>'Dates');

unset($fruits[2]); //delete "Dates"

unset($fruits_2['red']); //delete "Apples“

?>

removing_items_from_arrays.php
ITERATING THROUGH ARRAYS
 Accessing an entire array
 We have seen how to access individual elements using key
o Require a prior knowledge of the key

 To access all elements, use foreach loop The loop will iterate through
foreach ($array as $value) { every element in $array,
assigning each element’s
// Do something with $value. value to the $value variable
}
<?php
$fruits=array('Apples','Bananas','Dates','Oranges');
/*iterating through an array */
foreach($fruits as $value) {
echo $value;
}?>
looping_through_an_array.php
ITERATING THROUGH ASSOCIATIVE
ARRAYS
 To access both the keys and values, use
foreach ($array as $key => $value) {
echo "The value at $key is $value.";
}
<?php

$fruits=array('red'=>'Apples','yellow'=>'Bananas',
'beige'=>'Cantaloupes','brown'=>'Dates');

$var=$fruits['red']; //the value is ‘Apples’

//iterating through the array


foreach ($fruits as $key => $value) {
echo "Fruits[$key]=$value <br>";
}
associative_arrays.php
<?php The values in
associative arrays are
$fruits=array('red'=>'Apples','yellow'=>'Bananas', not arranged based on
'beige'=>'Cantaloupes','brown'=>'Dates');
integer indexes.
$var=$fruits[‘red’]; //the value is ‘Apples’
The values are arranged
//iterating through the array based on keys instead.
foreach ($fruits as $key => $value) {
echo "$key:$value"; For instance, the key of
} “apples” is “red”.
//an alternative way for iterating through the array
while(list($key,$value)=each($fruits)){ Keys must be unique.
echo "$key:$value"; Values don’t have to be.
}
Key Value
?>
Red ‘Apples’
Yellow ‘Bananas’
Beige ‘Cantaloupes’

Brown ‘Dates’
ARRAYS
 Example
arrays.php
<?php
// Make the months array:
$months = array ('January’, 'February', 'March', 'April’, 'May’,
'June', 'July', 'August', 'September’, 'October’,
'November', 'December’);

// Make the months pull-down menu:


echo ‘the list of keys and values in the array are’;
foreach ($months as $key => $value) {
echo “<br />$key::$value“;
}
?>
ARRAY FUNCTION
 Some interesting functions
 count(): returns the number of element in an array

$num = count($array);
 Is_array(): checks if the variable is of type array
 explode()
Takes a string containing several items separated by a single character (or a
string of characters) and place each of these items into an array containing all
its words.
Example:
$temp=explode(' ', “This is a sentence”);
The value of $temp is:
Array( [0]==> This
[1]==>is
[2]==> a
[3]==> sentence
) array_functions.php
ARRAY FUNCTION
Function Description Example

sort Sorts an array in ascending order. sort($fruits)


Other variants include:
sort($fruits, SORT_NUMERIC);//sorts numerically
sort($fruits, SORT_STRING); //sorts as strings

rsort Sorts an array in descending order. rsort($fruits)

asort Sorts associative arrays in ascending order, according to the asort($fruits_2)


value
ksort Sorts associative arrays in ascending order, according to the key ksort($fruits_2)

arsort Sorts associative arrays in descending order, according to the arsort($fruits_2)


value
krsort Sorts associative arrays in descending order, according to the krsort($fruits_2)
key

usort Sorts an array based on a user-defined sort usort($fruits,”cmp”)


;
ARRAYS
 Multidimensional arrays
 An array’s values could be any combination of :
o numbers
o Strings
o other arrays

This last case creates a


multidimensional array
ARRAYS
 Multidimensional arrays: Example
Use an array to maintain the list of students and
for each student maintain the list of courses
she/he is registered in.
ARRAYS
 Multidimensional arrays: Example

Step 1: declare an array for list of students


$students = array (‘M123’, ‘M345’, M567’);

Step 2: for each student, create an array maintain the courses


he/she is registered in
$student1 = array (‘CIT499’, ‘NET455’, ‘SEC460’);
$student2 = array (‘MTH215’, ‘MTH281’, ‘SWE245’);
$student3 = array (‘SEC235’, ‘NET351’, ‘ARA300’);

Step3: Combine all of the arrays into one


$registrations = array(
$students[0] => $student1,
$students[1] => $student2,
$students[2] => $student3);
ARRAYS
 Access multiterminal content
What is the first course that the second student is registered in.
echo $registrations['M123'][0]; OR
echo $registrations[$students[0]][0];

Print the whole content of the multidimensional array


o Two foreach are needed
foreach ( $registrations as $key => $value) {
echo "<br /><b>$key</b>";
foreach $value as $k => $v) {
echo "<br />[$k]=$v";
}
}
EXAMPLE
makes three pull-down menus for an HTML form: months,
days, years.

calendar.php
CORRECT THE PATTERNS
QUESTION LAB-4
ANY QUESTIONS?

27
REFERENCES
• PHP
• https://www.w3schools.com/php/php_arrays.asp
• https://www.w3schools.com/php/php_arrays_multi.asp

• http://php.net/manual/en/langref.php

28

You might also like