Web App Prog CH3
Web App Prog CH3
Web App Prog CH3
3
If you think about computer
programming, it’s as
antisocial as it gets.
Arrays are complex variables that store a group of values under a single variable name.
You can use an array to stored related values that you want to process as a group. Each
value in an array is called an element. An array can have as many elements as needed.
You do not need to specify the size of an array. PHP will store the array with as many
elements as you assign to it. Each element in an array has a key so that you can access the
individual element. You assign value to an array as follow:
$arrayname [‘key’] = value1;
$arrayname[‘key’] = value2;
23 | P a g e C h a p t e r 3 : U s i n g A r r a y s
You can use numbers or strings as key. String keys should be enclosed in single quotes such
as $arrayname[‘cost’]. If you do not include a key in the square bracket, PHP assigns a
numeric key, starting with 0 as the first element, not 1. Arrays with string key are called
associative arrays. The values can be any data type. You can add another element to the
array at any location in the script with a similar assignment statement.
You can create an array with an array statement, with the following format:
$arrayname = array (“key1” => value, “key2” => value,…);
You can leave out the keys in the statement, in which case PHP assigns numeric keys. You
can display array values with the var_dump and print_r statement.
Example:
1. Create an array, letting PHP assign the keys.
2. Create an array using the array statement. Keys are specifies in the array statement.
The array statement is written with one element on each line. This is not required by
PHP. The formatting is used to make the script easier for human to read.
3. Add var_dump statement to display the content of an array. <pre> tags enclose the
var_dump statement to display the output in a more readable format.
4. Add echo statement that display one element of an array.
5. Vie the script in a browser. The output from the var_dump statement is formatted in
multiple lines. The echo statements show the value of one array element.
24 | P a g e C h a p t e r 3 : U s i n g A r r a y s
3.2 Modify or Remove an Array
You can modify an array by changing the value in an element or by removing or adding
one or more elements. You can change the value in an element with an assignment
statement. The value assigned in the new assignment statement replaces the current value
of the element. You can remove the value from an element by assigning NULL to it or by
assigning a string of zero length to the element. The element remains but it contains no
value. If you echo the element, nothing is displayed. No error message is displayed because
the element exists, but no value appears because the element contains no value.
You can also use the shortcut notations on an element that you can use on a variable, such
as ++ to increment the element by one, +=3 to add three to the element or .= to append a
value to the end of the current value. You can add an element at any point in the script
with an assignment statement that assigns a value to an element with a new key. You can
remove an element from an array with the unset statement as follow:
unset ($arrayname [‘key’]); if you echo an element that does not exist, either because
it was never added to the array or because it was removed from the array, you will see a
notice similar to the following:
Notice: Undefined index: key in …………….. on line 10.
The message display the key that PHP could not find in the array. You can remove the entire
array with the unset statement as follows:
unset ($arrayname);
25 | P a g e C h a p t e r 3 : U s i n g A r r a y s
3.3 Walk through an Array
You will often want to perform an action on every element in an array, such as echo value
store each value in a database or add 5 to each value. Walking through each and every
element in an array is called iteration or traversing an array. In most cases using foreach
loop is the easiest and most efiecient way to walk through an array. The general format is
as follows:
foreach ($arrayname as $keyname => $valuename)
{
Block of PHP statement
}
$arrayname is the array that you want to walk through. In the foreach statement, $keyname
and $valuename are variable names that the foreach loop gives to the key and the value
of each element in turn. You can then use the variable names in the block of PHP does not
require you to indent the statement in the block but indenting makes the script much easier
to understand and debug.
You can leave $keyname => out of the foreach statement. When $keyname is left out, the
foreach loop only executes the block of statement on the value of each element. PHP
makes a copy of the array that traversed in the foreach loop. Therefore changes made in
the loop are not changed in the original array unless you specifically save the new values
in the original array.
You often want to perform an action on several elements in an array. If you want to perform
an action on every element in order, you probably want to use a foreach loop. However
you sometimes want to perform an action on every second or third element or each
element in reverse order. Traversing the array manually enables you to select elements in
the order that you need. You can select elements in an array manually with a pointer. Think
of you array as a list with a pointer pointing to an element in the list. The pointer stays ion an
element until you move it. After you move it, it points to the destination element until you
move it again.
26 | P a g e C h a p t e r 3 : U s i n g A r r a y s
The first time that access the array, the pointer is located at the first element. If you are
unsure where the pointer is located, you can move it to the first element with the reset
statement or the last element with the end statement, as follows;
reset($arrayname);
To access value within the array, PHP provides the functions current (), which refers to the
element currently under the pointer and does not move the pointer; next (), which moves
the pointer back one element. The functions move the pointer and return the value of the
element that is the pointer destination, as in the following statement;
$value = nex ($arrayname);
After the statement, $value contains the value of the next element in the array.
There are three different kinds of arrays and each array value is accessed using an ID which
is called array index. Numeric array is an array with a numeric index. Values are stored and
accessed in linear fashion. Associative array − An array with strings as index. This stores
element values in association with key values rather than in a strict linear index order.
Multidimensional array − An array containing one or more arrays and values are accessed
using multiple indices
Numeric Array
These arrays can store numbers, strings and any object but their index will be represented
by numbers. By default array index starts from zero.
27 | P a g e C h a p t e r 3 : U s i n g A r r a y s
Associative Array
The associative arrays are very similar to numeric arrays in term of functionality but they are
different in terms of their index. Associative array will have their index as string so that you
can establish a strong association between key and values.
Multidimensional Array
A multi-dimensional array each element in the main array can also be an array. Each
element in the sub-array can be an array, and so on. Values in the multi-dimensional array
are accessed using multiple indexes.
28 | P a g e C h a p t e r 3 : U s i n g A r r a y s
3.5 Store a Set of Variables in an Array
Sometimes you want to store the information from a set of variables in an array. If you want
to perform an operation on each variable in a set of variable such as display each value
or add a number to each variable value, you can do this more efficiently if you store the
variable values in an array. You can use one foreach statement to access the variable
values one at a time, rather than write several statement to access each variable
separately.
You can use the compact statement to store variable values in an array. The variable
names become the keys of the array. The format is
($array_out = compact (“varname1”, “varname2”, $array_of_names,…);
You can provide the variable names as strings, as an array of variable names, or as a
combination of both. After the compact statement, the array contains elements for each
variable name provided, with the variable name as the key. The compact function adds
an element to the array for every variable name passed to it that it can find. If it cannot
find one or more of the variables specified by a string, it does not add it to the array , but it
does not display an error message. It just ignores the variables it cannot find. If compact
cannot find any of the variable names passed to it, it creates an array with zero elements.
However, if an array of variable names is included in the compact statement and the array
does not exist, a notice for an “Underfined variable: “ is displayed, before the array with
zero elements is created.
Sometimes you want to store the information from array elements in separate variables. For
example, if you need to echo different elements on a Web page, it can be more efficient
to create separate variables for each element and display the variables where needed.
PHP provides a function that creates the set of variables for you. You can use the extract (
) statement to store the array information in a set of variables, as follow:
extract ($arrayname) ;
The extract ( ) function creates a variable for each element in the array. The variable name
is the key for the element. The extract ( ) function dies not affect the original array; the
original array continues to exist as is. The extract ( ) function just creates a new set of
variables.
29 | P a g e C h a p t e r 3 : U s i n g A r r a y s
Beginning with PHP 4.0.5, the extract ( ) function returns an integer that is the number of
variables created, as follows:
If you pass an array name to the extract ( ) function that does not exist, extract ( ) displays
a notice for an “Underfined variable: “. If you pass an array name that is variable rather
than an array, the extract ( ) function displays the following warning:
Warning: extract ( ) : First argument should be an array in C:\Program
Files\Apache Group\Apache2\htdocs\PHPMySQL\arrays\extract.php on line 16
PHP has several built-in arrays that you can use when writing PHP scripts. These arrays, listed
in the table below, are called superglobal arrays because they have a global scope.
Scope refers to the superglobal arrays are available anywhere in your program, including
in functions. Different types of information are stored in different arrays. The table below
lists the superglobal arrays and the type of information stored in them. The following built-
in arrays are available only if track-vars is enabled. As of PHP 4.0.3, track-vars is always
enabled, unless the PHP administrator deliberately turns it off – a rare occurrence.
PHP Arrays
The following table describes the most widely used built-in arrays, called superglobals or
automatic global arrays.
ARRAY DESCRIPTION
$_POST Contains all the variable submitted in a form that uses the POST method.
$_GET Contains the entire variable passed in the URL. This includes all variable submitted in a form
that uses the GET method and any variables manually added to the URL.
$_COOKIES Contain the entire cookies variable.
$_REQUEST Contains the variable that are in $_POST, $_GET, and $_COOKIES.
$_SESSION Contains all session variable.
$_FILES Contain the names of files that have been uploaded.
$_SERVER Contains information about your server. Because your web server provides the information,
the information that is available depends on which server you are using.
$_ENV Contains information provided by your operating system, such as the operating system
name. This information varies depending on your operating system.
$_GLOBALS Contain the entire global variable, including all variable you create in your script.
30 | P a g e C h a p t e r 3 : U s i n g A r r a y s
Using PHP Arrays
You can use PHP arrays the same way that you use the arrays you create yourself. You can
display them with var_dump and print_r. You can use any of the array values in your script,
using an array notation, such $_POST [‘key’]. You can use a PHP built-in array value
anywhere you can use a variable, just as you can use a value from your own array
anywhere you can use a variable. The variable that you create yourself are added to the
$GLOBALS array. You can then access the variable from the $GLOBALS array anywhere in
your script. For example a variable that you assign a value to in your script can be accessed
inside a function as $GLOBALS [‘varname’].
Form Variables
PHP makes it simple to process the information that a user submits in a form. When the user
clicks the submit button, the information in the form fields is passed to the processing script,
where the information is available in the $_POST array forms that use the POST method and
in the $_GET array for forms that use the GET method. Both POST and GET variable are
available in the $_REQUEST array. The values from the form are stored in the array with
filename as the keys. If you want to process every value from the form, you can use a
foreach statement to loop through the $_POST array, as follow:
foreach($_POST as $key => $value)
{
block of PHP statements
}
The $_SERVER and $_ENV arrays contain different information, depending on the server and
operating system you are using. You can see some of the information in the arrays in the
output form the phpinfo () statement. You can see all the values in the arrays for your
particular server and operating system with a var_dump statement. One useful value in the
$_SERVER array is $_SERVER [‘DOCUMENT_ROOT’] which contains the path to your web space
the location where your web server expect to find the web page files. Another useful
element in the $_SERVER array is $_SERVER [‘PHP_SELF’]. This element shows the file that
contains the script that is currently running.
31 | P a g e C h a p t e r 3 : U s i n g A r r a y s
Built-In Array in Older Php Versions
The built-in arrays shown the table were introduced to PHP in version 4.1.0 with the exception
of $GLOBALS which has been available since PHP 3. An older set of built-in array is available
that PHP had provided since earlier versions. The older PHP arrays are named with a longer
format such as;
32 | P a g e C h a p t e r 3 : U s i n g A r r a y s