Let us first look at how standard variables are defined in PHP. If we
want to make an integer variable, by the name of 'roll', we write the
following PHP code,
<?php
//Integer Variable
$roll = 4429;
?>
An array is actually a collection of variables. The formal definition
of an array is actually 'an ordered map'. In most of the languages, the
various elements of the array must be of the same type. For example,
all the elements must be integers or characters, but it is not so in
PHP. Lets look at a code example to define an array,
<?php
//Array Example
$roll[0] = 1;
$roll[1] = 2;
$roll[2] = 3;
?>
Notice, that similar to ther languages, the array subscripts in PHP
start from zero. Another easier, and much shorter way of defining
arrays is,
<?php
//Another array example
$name = array('rae', 'slayer', 'quest');
?>
Notice that in the second case, you will have to use the built in
'array()' function, while that is not required in the first case. There
are certain rules to be follwed while choosing array names, but they
are not hard to remember since the same rules apply to choosing any
variable names in PHP : it must begin with a letter or underscore, and
can optionally be followed by more letters, numbers and underscores.
To print the array, we use the 'print_r' function. Now, in all
practical circumstanes, this function is used more for its debugging
usefulness rather than its output. Output of arrays makes more sense
when it is done in a tabular format using loops. Here is an example of
using this function,
<?php
//array printing function example
$name = array('rae', 'slayer', 'quest');
print_r($name);
?>
Now, the big question that arises in the mind of anyone who hasn't used
arrays in any programming language before is, why use them? And the
answer is very simple, they make life easier. Supposing you had to
output say fifty values, you can't write fifty echo statements, instead
an elegant solution is to use loops and arrays as shown below,
<?php
.... //previous unnecessary code
//code to show benefits of using arrays
foreach($name as $customer) {
?? echo "$customer
n";
}
?>
There is another interesting characteristic of arrays in PHP. Instead
of using numeric subscripts for arrays, you can define 'keys'. Below is
an example to illustrate this,
<?php
//example of keys
$menu['name'] = 'rae';
$menu['member'] = 'cyberarmy';
$menu['brigade'] = 'university';
?>
As we have in other programming languages, in PHP also, we have the
facility of multi-dimensional arrays. This is quite useful in the case
of representing matrices. A two dimensional array is defined using two
subscripts. Below is an example,
<?php
//two dimensional array example
echo $name[0][0]
echo $name[0][1]
?>
The subscript [0][0] means the first element of the two dimensional
array, followed by [0][1], [1][0], [1][1].
References
http://www.zend.com
http://codewalkers.com
Written by Rae
This article was originally published by CyberArmy.net in the CyberArmy Library.
|