Professional Documents
Culture Documents
Formulated:
Saniat Obaidullah
Zend Certified Engineer
_______________________________________________________________________________________________________________
PHP Bible, 2nd Edition 1 Wiley and the book authors, 2002
Summary
_______________________________________________________________________________________________________________
PHP Bible, 2nd Edition 2 Wiley and the book authors, 2002
Uses of Arrays
Arrays are definitely one of the coolest and most flexible
features of PHP. Unlike vector arrays from other languages (C,
C++, etc.), PHP arrays can store data of varied types and
automatically organize it for you in a large variety of ways.
Some of the ways arrays are used in PHP include:
Built-in PHP environment variables are in the form of arrays (e.g.
$_POST)
Most database functions transport their info via arrays, making a
compact package of an arbitrary chunk of data
It's easy to pass entire sets of HTML form arguments from one
page to another in a single array
Arrays make nice containers for doing manipulations (sorting,
counting, etc.) of any data you develop while executing a single
page's script
_______________________________________________________________________________________________________________
PHP Bible, 2nd Edition 3 Wiley and the book authors, 2002
What are PHP arrays
PHP arrays are associative arrays with a little extra thrown in.
The associative part means that arrays store element values in
association with key values, rather than in a strict linear index
order
If you store an element in an array, in association with a key, all
you need to retrieve it later from that array is the key value
$state_location['San_Mateo'] = 'California';
$state = $state_location['San_Mateo'];
If you want to associate a numerical ordering with a bunch of
values or just store a list of values, all you have to do is use
integers as your key values
$my_array[1] = 'The first thing';
$my_array[2] = 'The second thing';
_______________________________________________________________________________________________________________
PHP Bible, 2nd Edition 4 Wiley and the book authors, 2002
Associative vs. vector arrays
In vector arrays (like those used in C/C++), the contained
elements all need to be of the same type, and usually the
language compiler needs to know in advance how many such
elements there are likely to be
double my_array[100]; // this is C
Consequently, vector arrays are very fast for storage and lookup
since the program knows the exact location of each element and
they are stored in a contiguous block of memory
PHP arrays are associative (and may be referred to as hashes)
Rather than having a fixed number of slots, PHP creates array
slots as new elements are added to the array and elements can
be of any PHP type
_______________________________________________________________________________________________________________
PHP Bible, 2nd Edition 5 Wiley and the book authors, 2002
Creating arrays
There are 4 main ways to create arrays in PHP
Direct assignment
Simply act as though a variable is already an array and assign a
value into it
$my_array[1] = 1001;
The array() construct
Creates a new array from the specification of its elements and
associated keys
Can be called with no arguments to create an empty array (e.g. to
pass into functions which require an array argument)
Can also pass in a comma-separated list of elements to be stored and
the indices will be automatically created beginning with 0
$fruit_basket = array('apple','orange','banana','pear');
o Where $fruit_basket[0] == 'apple', $fruit_basket[1] == 'orange', etc.
_______________________________________________________________________________________________________________
PHP Bible, 2nd Edition 6 Wiley and the book authors, 2002
Creating arrays (cont.)
Specifying indices using array()
If you want to create arrays in the previous manner but specify the
indices used, instead of simply separating the values with commas,
you supply key-value pairs separated by commas where the key and
the value are separated by the special symbol =>
$fruit_basket = array ('red' => 'apple',
'orange' => 'orange',
'yellow' => 'banana',
'green' => 'pear');
Functions returning arrays
You can write your own function which returns an array or use one
of the built-in PHP functions which return an array and assign it to a
variable
$my_array = range(6,10);
o Is equivalent to
$my_array = array(6,7,8,9,10);
o Where $my_array[0] == 6;
_______________________________________________________________________________________________________________
PHP Bible, 2nd Edition 7 Wiley and the book authors, 2002
Retrieving values
The most direct way to retrieve a value is to use its index
If we have stored a value in $my_array at index 5, then
$my_array[5] will retrieve that value. If nothing had been stored
at index 5 or if $my_array had not been assigned, $my_array[5]
will behave as an unbound variable
The list() construct is used to assign several array elements
to variables in succession
$fruit_basket = array('apple','orange','banana');
list($red_fruit,$orange_fruit) = $fruit_basket;
The variables in list() will be assigned the elements of the
array in the order they were originally stored in the array
_______________________________________________________________________________________________________________
PHP Bible, 2nd Edition 8 Wiley and the book authors, 2002
Multidimensional arrays
The arrays we have looked at so far are one-dimensional in that
they only require a single key for assigning or retrieving values
PHP can easily support multiple-dimensional arrays, with
arbitrary numbers of keys
Just like one-dimensional arrays, there is no need to declare our
intensions in advance, you can just assign values to the index
$multi_array[1][2][3][4][5] = 'deep treasure';
Which will create a five-dimensional array with successive keys that
_______________________________________________________________________________________________________________
PHP Bible, 2nd Edition 9 Wiley and the book authors, 2002
Multidimensional arrays (cont.)
$cornucopia = array('fruit' => array('red' => 'apple',
'orange' => 'orange',
'yellow' => 'banana',
'green' => 'pear'),
'flower' => array('red' => 'rose',
'yellow' =>
'sunflower',
'purple' => 'iris'));
$kind_wanted = 'flower';
$color_wanted = 'purple';
print("The $color_wanted $kind_wanted is
{$cornucopia[$kind_wanted][$color_wanted]}");
Function Behavior
is_array() Takes a single argument of any type and returns a true
value if the argument is an array, false otherwise
count()/sizeof() Takes an array as an argument and returns the number
of nonempty elements in the array (1 for strings & #s)
in_array() Takes 2 arguments, the element you are looking for
and the array it may be in. If the element is contained
as a value in the array, it returns true, otherwise false
IsSet($array[$key]) Takes an array[key] form and returns true if the key
portion is a valid key for the array
_______________________________________________________________________________________________________________
PHP Bible, 2nd Edition 11 Wiley and the book authors, 2002
Deleting from arrays
Deleting an element from an array is just like getting rid of an
assigned variable calling the unset() construct
unset($my_array[2]);
unset($my_other_array['yellow']);
_______________________________________________________________________________________________________________
PHP Bible, 2nd Edition 12 Wiley and the book authors, 2002
Iteration
Iteration constructs provide techniques for dealing with array
elements in bulk by letting us step or loop through arrays,
element by element or key by key
In addition to storing values in association with their keys, PHP
arrays silently build an ordered list of the key/value pairs that
are stored, in the order that they are stored for operations that
iterate over the entire contents of the array
Each array remembers a particular stored key/value pair as
being the current one, and array iteration functions work in part
by shifting that current marker through the internal list of keys
and values
This is commonly referred to as the iteration pointer, although
PHP does not support full pointers in the sense that C/C++
programmers may be used to
_______________________________________________________________________________________________________________
PHP Bible, 2nd Edition 13 Wiley and the book authors, 2002
Our favorite iteration method: foreach
Our favorite construct for looping through an array is foreach which is
somewhat related to Perl's foreach, although it has a different syntax
There are 2 flavors of the foreach statement
foreach (array_expression as $value_var)
loops over the array given by array_expression. On each loop, the value of
the current element is assigned to $value_var and the internal array pointer
is advanced by one (so on the next loop, you'll be looking at the next
element)
foreach (array_expression as $key_var => $value_var)
does the same thing, except that the current element's key will be assigned to
the variable $key_var on each loop
array_expression can be any expression which evaluates to an array
When foreach first starts executing, the internal array pointer is
automatically reset to the first element of the array. This means that you do
not need to call reset() before a foreach loop
_______________________________________________________________________________________________________________
PHP Bible, 2nd Edition 14 Wiley and the book authors, 2002
foreach example
If you would like to see each of the variables names and values
sent to a PHP script via the POST method, you can utilize the
foreach construct to loop through the $_POST array
print ('<TABLE><TR><TH>Name</TH>'.
'<TH>Value</TH></TR>');
foreach ($_POST as $input_name => $value)
{
print ("<TR><TH>$input_name</TH>".
"<TD>$value</TD></TR>\n");
}
print ('</TABLE>');
_______________________________________________________________________________________________________________
PHP Bible, 2nd Edition 15 Wiley and the book authors, 2002
Iterating with current() and next()
foreach is useful in situations where you want to simply loop through an
array's values
For more control, you can utilize current() and next()
The current() function returns the stored value that the current array
pointer is pointing to
When an array is newly created with elements, the element pointed to
returns false
If false is a value stored in the array, next will return false even if it has
_______________________________________________________________________________________________________________
PHP Bible, 2nd Edition 19 Wiley and the book authors, 2002
Transformations of arrays
PHP offers a host of functions for manipulating your data once
you have nicely stored it in an array
The functions in this section have in common is that they take
your array, do something with it, and return the results in another
array
array array_keys (array input [,mixed search_value])
returns the keys, numeric and string, from the input array.
If the optional search_value is specified, then only the keys for
that value are returned. Otherwise, all the keys from the input are
returned.
array array_values ( array input) returns all the values from
the input array and indexes numerically the array
Simply returns the original array without the keys
_______________________________________________________________________________________________________________
PHP Bible, 2nd Edition 20 Wiley and the book authors, 2002
More array transformation functions
array array_count_values ( array input) returns an array
using the values of the input array as keys and their frequency in input as
values
In other words, array_count_values takes an array as input and
returns a new array where the values from the original array are the keys
for the new array and the values are the number of times each old value
occurred in the original array
array array_flip ( array trans) returns an array in flip order,
i.e. keys from trans become values and values from trans become keys
Although array keys are guaranteed to be unique, array values are not.
cannot be converted to keys are encountered, the function will fail and a
warning will be issues
_______________________________________________________________________________________________________________
PHP Bible, 2nd Edition 21 Wiley and the book authors, 2002
More array transformation functions
array array_reverse ( array array [, bool
preserve_keys]) takes input array and returns a new array with the
order of the elements reversed, preserving the keys if preserve_keys is
TRUE
void shuffle ( array array) shuffles (randomizes the order of
the elements in) an array
Note: calls to srand prior to shuffle is no longer necessary
key will overwrite the previous one. If, however, the arrays contain
numeric keys, the later value will not overwrite the original value, but
will be appended
_______________________________________________________________________________________________________________
PHP Bible, 2nd Edition 22 Wiley and the book authors, 2002
Sorting
PHP offers a host of functions for sorting arrays
As we saw earlier, a tension sometimes arises between respecting the
associations
A lack of an initial a or k means that it sorts by value but doesn’t
_______________________________________________________________________________________________________________
PHP Bible, 2nd Edition 25 Wiley and the book authors, 2002