http://www.chrispearson.org/pages/programming/php/array03.asp
13h04
Wednesday, 7. January 2009

PHP: ARRAYS

ARRAYS - GETTING AT THEIR ELEMENTS

If you read the previous page to the bitter end and followed the final code example you will have seen (If you didn't, try it now: shopping.php) that attempting to print an array using the same syntax as you'd use to print a scalar variable generates the output

Array

in the browser. But not an error.

In this section we will look at four ways that we can get sequential access to an array's elements and, in the examples, to print them. Once we've done that we'll move on to how we might access specific elements and then how we can change and delete existing elements and add more to an existing array. We can then cover ways to convert to and fro between arrays and strings. By that stage we have all the groundwork in place to start using advanced features in real web applications: processing forms, sorting results and more!

All of the following examples use the basic shopping.php page and the platform for our exercises.

The simplest way (the most straightforward, that is, but rather pedestrian) to print the values held in an array is to sequentially name them.

Change the print function in shopping.php to

print("The list array is
$shoppinglist[0]<BR>\n
$shoppinglist[1]<BR>\n
$shoppinglist[2]<BR>\n
$shoppinglist[3]<BR>\n
$shoppinglist[4]<BR>\n
");

Save the file as shopping02.php and browse to it (or follow this link to shopping02.php which contains this code)

The output from shopping02.php

The next is to create a program loop to generate the numerical keys for us. The downside of this technique is that we need to know how many elements the array has when we write the PHP code.

This uses a for loop, with a loop counter that also provides an index to the array elements. Taking shopping.php as the basis, delete the print function and, in its place, type this code

<?PHP
$shoppinglist = array("bread", "lemonade",
"apples", "potatoes", "coffee");
print("The list array is ");
for ($i = 0; $i < 5; $i++) {
   print("$i - $shoppinglist[$i]<BR>\n");
}

?>

and save it as shopping03.php. Notice here that we are printing the loop counter ($i) followed by space-hypen-space then the value of the array element, just so we can see what the code is doing, as shown on the right.

The counter in for ($i = 0; $i < 5; $i++) runs from zero to four (an integer less than five, in fact), incrementing by one each loop, so the programmer must know how many elements will be printed before the code is written.

Output using a for loop

The next technique allows us to loop and process every array element even when we don't know how many records there are when we write the code. In this instance we use built-in PHP function called count() which returns the number of elements in an array: In our example

count($shoppinglist)

returns 5, since there are five indices, 0, 1, 2, 3 and 4.

We can use count to set up the limit of a for loop. To do this, take the file shopping02.php and change the PHP code to

<?PHP
$shoppinglist = array("bread", "lemonade",
"apples", "potatoes", "coffee");
$itemcount = count($shoppinglist);
print("The list array contains $itemcount elements<BR>\n");
for ($i = 0; $i <
$itemcount; $i++) {
   print("$i - $shoppinglist[$i]<BR>\n");
}

?>

before saving the file as shopping04.php. Then browse to the page and look at the resulting output. Notice that we use the count of array elements, $itemcount, twice: Once to report back on the count and once to set up the for loop.

Output using a count of array elements and a for loop

The last of the four techniques uses each, a PHP language feature that allow us great flexibility in processes lists including arrays: each().

The principle benefit of using each is that you don't have to specify the index of the array element, which is what we've been doing in all the examples so far.

We'll look at two versions of a loop using each, the first of which requires only a minor change to shopping04.php. So, take shopping04.php and change the code to

<?PHP
$shoppinglist = array("bread", "lemonade",
" apples", "potatoes", "coffee");
$itemcount = count($shoppinglist);
print("The list array contains $itemcount elements<BR>\n");
for ($i = 0; $i < $itemcount; $i++) {
   $thiselement = each($shoppinglist);
   print($thiselement[ "key" ] . " - " .
      $thiselement[ "value" ] .
      "<BR>\n");
}
?>

then save the file as shopping05.php. Then browse to it and see the results - Not much change!

What we've done here it to place each element of $shoppinglist into $thiselement and use that to print both the element's index $thiselement["key"] and its value, $thiselement["value"]. Notice that I've split the literal text from the variables, using the dot to concatenate them for clarity, since the words key and value need to be quoted.

The output might be exactly the same but the seachange here is that we no longer need to specify the index of the element we're dealing with.

Output using each()

The second use of each() - and the final examples in this section - gets away from using the for loop with a counter and sets us up with the tools we need to exploit associative arrays. To fully benefit from the functionality of PHP in this area we will use another inbuilt function called list() but, before we introduce list() let's take a look at using a while() loop in place of the for() loop.

Taking shopping05.php as your starting point, amend the PHP code it contains like this

<?PHP
$shoppinglist = array("bread", "lemonade",
" apples", "potatoes", "coffee");
$itemcount = count($shoppinglist);
print("The list array contains $itemcount elements<BR>\n");
while ($thiselement = each($shoppinglist)) {
      print($thiselement[ "key" ] . " - " .
      $thiselement[ "value" ] .
      "<BR>\n");

}
?>

and save it as shopping06.php. Browse to it and note the output.

Notice now that the count() function is required only to report on the number of elements in the array and that each array element is sequentially referenced using each() and not by coding an index to it. The loop itself now continues, without a counter, from the first element to the last by using a while() function.

Using the list() function allows us to make the code neater and to provide an altogether more elegant and more flexible approach to array processing.

Taking shopping06.php as the starting point, edit the PHP code as follows:

<?PHP
$shoppinglist = array("bread", "lemonade",
" apples", "potatoes", "coffee");
$itemcount = count($shoppinglist);
print("The list array contains $itemcount elements<BR>\n");
while (list($index, $item) = each($shoppinglist)) {
      print("$index - $item<BR>\n");
}
?>

then save the file as shopping07.php.

The output may seem monotonously similar but the code is now compact and flexible.

THE list() FUNCTION

The list() function, when used with each(), will split an array element into two values, the element's key and its value. Its use allows these two values to be assigned to variables which make them easier to handle and makes the code easier to read and to understand.

So, the usage

list($keyvalue, $datavalue) = each($arrayname)

returns the key of the current array element in $keyvalue and its associated array value in $datavalue.

In the next section we will move on to processing arrays and how to use them in dynamic web pages

 

< Previous page: Creating a PHP array Next page: Processing arrays >

 

 

Top of this page

xxx,xxx

copyright ©2000 - 2009 Chris Pearson