Saturday, March 15, 2014

Arrays in PHP

In most languages, including PHP, an array is a collection of objects of the same data type. An array could consist of strings,  integers,  or virtually any other data type supported by PHP. Using array's can add some organization to code, when they are strategically used in place of local variables


To define an array, the following two syntax's can be used

1. Declaring and defining the array at the same time
$colors= array("blue", "green", "red", "yellow");

2. Declaring the array, and defining it later

$colors=array()
$colors[0]="blue"
$colors[1]="green"
$colors[2]="red"
$colors[3]="yellow"

No matter what syntax you used to define the array, individual array elements can be referenced by their position at a later point in time

echo $colors[1]
//would print "green"

In addition to referring to individual array elements, PHP allows a handful of sorting mechanisms for arrays:
  • sort() - sort arrays in ascending order
  • rsort() - sort arrays in descending order
  • asort() - sort associative arrays in ascending order, according to the value
  • ksort() - sort associative arrays in ascending order, according to the key
  • arsort() - sort associative arrays in descending order, according to the value
  • krsort() - sort associative arrays in descending order, according to the key
[provided by W3 schools]

Finally, a very useful feature with Arrays in PHP is the ability to manually choose and assign a key to each array element.
Picture a situation in which instead of referring to a colour by its number, we could use a person's name. This would be useful in a situation where we were keeping track favorite colours.

$age=array();
$favorite['jon']="green";
$favorite['mike']="red";
$favorite['sam']="blue";
$favorite['andrew']="yellow";


$favorite['jon'] would equal 'green'
echo "Jon's favorite colour is". $favorite['jon']



No comments:

Post a Comment