Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
43 views

PHP Arrays

This document discusses arrays in PHP. It covers numerically indexed arrays, associative arrays, creating and accessing arrays, sequential access using foreach loops, array operators, determining array size, and sorting arrays. The document provides examples and explanations of key array functions and concepts in PHP.

Uploaded by

Satvik Goswami
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views

PHP Arrays

This document discusses arrays in PHP. It covers numerically indexed arrays, associative arrays, creating and accessing arrays, sequential access using foreach loops, array operators, determining array size, and sorting arrays. The document provides examples and explanations of key array functions and concepts in PHP.

Uploaded by

Satvik Goswami
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 22

PHP

Using Arrays

1
Arrays
Topics:
Numerically indexed arrays
Non-numerically indexed arrays (hashes, associative
arrays)
Array operators
Multidimensional arrays - read
Array sorting
Other array functions
Complete reference for arrays at
http://www.php.net/array
2
Arrays
An array = a set of data represented by a single variable name
Example, the $products array:

In PHP, each array element consists of :


 A value
 A key or index that is used to access the element
 (internally, all arrays in PHP are associative = hashes…)
The keys / indexes can be:
 Non-negative integers → these PHP arrays have the logical structure
similar to a classic array in other languages (Java, C) and can be used in
the traditional way
 Strings → associative arrays or hashes
 Mixture of both
3
Creating Numerically Indexed Arrays
Create a numerically-indexed (shortly indexed) array with
the language construct array:
Syntax:
$array_name = array(values);
Examples:
$products = array(‘Tires’, ‘Oil’, ‘Spark Plugs’);
$list = array(2, 4, 6, 8);
Keys are automatically 0, 1, 2 etc.
Note: $array_name = array(); creates an empty array

4
Creating Numerically Indexed Arrays
Create an indexed array by assigning a value to an element of
an array that doesn’t exist (the array!):
$array_name[index] = value; or $array_name[] = value;
Writing to an indexed array with empty [ ] creates the new element at
end of the array  PHP arrays don’t have fixed length!
Example:
$list = array(2, 4, 6, 8);
$list[ ] = 10;  $list is now array(2, 4, 6, 8, 10)
Example:
$Provinces[] = "Newfoundland and Labrador";
$Provinces[] = "Prince Edward Island";
if $Provinces didn’t exist before, it is created and has 2 elements,
indexed 0 and 1.
5
Creating Numerically Indexed Arrays
Other ways to create indexed arrays:
$new_array = $existing_array; // as a single unit
The range(…) function creates an array with a range of values
 Can be used with either numbers or characters (single letters)
 $n = range(4, 7); is same as $n = array(4, 5, 6, 7);

 $c = range(‘p’, ‘s’); is same as $c = array(‘p’, ‘q’, ‘r’, ‘s’);


A third parameter allows to specify a step size between values:
$odds = range(1, 10, 2); creates an array containing (1, 3, 5, 7, 9)
Load an array contents directly from a file
Load an array contents directly from a database
Functions to extract parts of an array or reorder an array
6
Creating Associative Arrays (Hashes)
Create an associative array with the language construct array:
 $prices = array(‘Tires’ => 100, ‘Oil’ => 10, ‘Spark Plugs’ => 4);
 $hash = array(‘QB’ => “Palmer”, ‘WR’ => “OchoCinco”, …);
 After first keys, if you don’t supply more, you get numeric keys starting
from 0:
$mixed = array('QB' => "Palmer", 'WR' => OchoCinco', 'Smith',
'Williamson');
 'Smith‘ is indexed 0, 'Williamson‘ is indexed 1
Create an associative array by assigning a value to an element of
an array that doesn’t exist (the array!):
 $prices[‘Tires’] = 100;
$prices[‘Oil’] = 10;
$prices[‘Spark Plugs’] = 4;
7
Accessing Array Contents
Use array name plus the index / key in square brackets to
access array elements.
$Provinces[0]
$prices[‘Tires’] or $prices[“Tires”]
The quotes around the string keys are optional for single-word
keys (a warning might be generated), but generally are used
However, quotes cannot be used when interpolating an
element of an array; solutions:
Don’t rely on interpolation, e.g. use instead regular string
concatenation: echo “The price for tires is”. $prices[‘Tires’];
Omit quotes: e.g. echo “The price for tires is $prices[Tires]”;

8
Creating Arrays
http://cscdb.nku.edu/csc301/frank/PHP_Arrays/arrays_cre
ating.php

9
Accessing Array Contents
Read/modify an array element’s value as usual
Writing to array with a currently-undefined key (or beyond the
end of an indexed array) creates a new element.
Use the unset(…) function to eliminate:
An array:
$products = array(‘Tires’, ‘Oil’, ‘Spark Plugs’);
unset($products); // $products doesn’t exist after this statement
An array element:
$products = array(‘Tires’, ‘Oil’, ‘Spark Plugs’);
unset($products[0]);
// $products remains with 2 elements only, indexed 1 and 2
10
Sequential Access to Array Elements
Logical internal structure of arrays:
 elements are stored in a linked list of cells;
 each cell includes both the key and the value of the element;
 cells are linked in the order they are created - numerically indexed arrays too 
classic arrays are ordered by index, PHP arrays are ordered by creation order
 array elements can be can accessed in creation order or key order if
keys are numbers

11
Sequential Access to Array Elements
Regular for loops for numerically indexed arrays:

$products = array('Tires', 'Oil', 'Spark Plugs');


for ($i=0; $i<3; $i++) {
echo $products[$i] . ", ";
}

12
Sequential Access to Array Elements
Foreach loops, specially designed for arrays, can be used
for all types of indexes.
For numerically indexed arrays, use:
foreach($arrayName as $val)
$val steps through each of the values in $arrayName

For associative arrays, you can also use:


foreach($arrayName as $key => $val)
$key and $val are set to each key - value in the hash in turn (in
the defined order = creation order)

13
Sequential Access to Array Elements
Foreach loops, examples:

$products = array('Tires', 'Oil', 'Spark Plugs');


foreach ($products as $val) {
echo $val . ", ";
}

$prices = array('Tires' => 100, 'Oil' => 10, 'Spark Plugs' => 4);
foreach ($prices as $key => $val) {
echo "$key - $val, ";
}

14
Sequential Access to Array Elements
Important - to modify the array elements’ values in a foreach
loop, use the reference operator:

$prices = array('Tires' => 100, 'Oil' => 10, 'Spark Plugs' => 4);
foreach ($prices as $key => &$val) {
$val *= 1.05; // increases product prices by 5%
}

By using &, $val will successively be an alias (alternative


name) for each array element value, instead of being a
separate variable that holds a copy of the array element
value!
15
Sequential Access to Array Elements
Each array has an internal pointer (or marker) that references one
element in the array → called current pointer
Various functions exist to (in)directly manipulate
this pointer to navigate in the array:
reset($a) sets the current element of array $a
to the start of the array; returns $a’s first element
end($a) sends the pointer to the end of the
array $a; returns last array element
current($a) or pos($a) return the array element
pointed to by the current pointer
next($a) and each($a) advance the pointer forward one element; return
the current element before (each) / after (next) advancing the pointer
prev($a) is the opposite of next()
16
Array Operators
Most of them have an analogue in the scalar operators, but with a
different meaning!
+ $a + $b performs the union of $a and $b arrays; $b is appended to $a,
except for $b’s elements that have the same keys as some elements
already in $a, which are not added
== $a ==$b is true if $a and $b contain the same elements
= = = $a ==$b is true if $a and $b contain the same elements, with the same
type, in the same order
!= $a !=$b is true if $a and $b do NOT contain the same elements
<> Same as !=
!= = $a !==$b is true if $a and $b do NOT contain the same elements, with
the same type, in the same order

17
Size of an Array
Two functions get the number of elements of an array passed to
them; return 0 for an empty array and 1 for a scalar variable:
count($a )
sizeof($a)
array_count_values($array_name) returns an associative array with:
keys = the distinct values from $array_name
the value for each key is the number of times that key occurs in
$array_name
Example: $list = array(1, 2, 6, 6, 6, 2);
$c = count($list); // $c contains 6
$ac = array_count_values($list);// $ac contains 1=>1, 2=>2, 6=>3
18
Sorting Arrays
3 types of sort:
Indexed array – sort values and reset indexes
Hash – sort by values
Hash – sort by keys

3 ways to sort (function names follow above order):


Ascending – sort( ), asort( ), ksort( )
Descending – rsort( ), arsort( ), krsort( )
User-defined – usort( ), uasort( ), uksort( )

19
Sorting Arrays
The ascending and descending sort routines are just called
with the array name
 ascending/descending sort() also take an optional argument that
specifies the sort type: SORT_REGULAR (the default; alphabetically
for strings, numeric order for numbers), SORT_NUMERIC, or
SORT_STRING
They sort the original array
User-defined sort takes second argument
 The name of a function that returns <0, 0 or >0 given 2 input
arguments based on their relative order (<0 means 1st is less than 2nd)

20
Arrays Sorting
http://cscdb.nku.edu/csc301/frank/PHP_Arrays/arrays_sor
ting.php

21
Loading Arrays from Files
Recall that file($file_name) returns the entire file content as an array:
each line in the file is one element of this array.
A line can be split into fields using
array explode(string $separator, string $line_string [, int $limit])
Ex: $s = "15:42, 20th April\t4 tires\t1 oil\t6 spark plugs\t$434.00\t22 4th St, Troy";
$a = explode (“\t”, $s);
// $s is exploded into: "15:42, 20th April", "4 tires", "1 oil", "6 spark plugs",
// "$434.00", and "22 4th St, Troy", which are stored in the array $a
The optional limit parameter can be used to limit the number of parts returned
Opposite for explode(): string implode(string $separator, array $arr)
it combines an array’s elements’ values into a single string, separated by the
specified separator

22

You might also like