PHP Tutorials - Herong's Tutorial Notes
Dr. Herong Yang, Version 2.21

Arrays

Part:   1  2 

PHP Tutorials - Herong's Tutorial Notes © Dr. Herong Yang

Non ASCII Characters with MySQL

Inputting Non ASCII Characters

Controlling Response Header Lines

HTTP Request Variables

Sessions

Using Cookies

PHP SOAP Extension

PHP SOAP Extension - Server

Directories, Files and Images

Using MySQL with PHP

... Table of Contents

(Continued from previous part...)

Here is the output:

Library hours:
Array
(
    [Monday - Friday] => 09:00 - 21:00
    [Saturday] => 09:00 - 17:00
    [Sunday] => closed
)

Prime numbers:
Array
(
    [0] => 3
    [1] => 5
    [2] => 7
    [3] => 11
    [4] => 13
)

Fruits:
Array
(
    [0] => Apple
    [1] => Orange
    [] => Banana
    [G] => Grape
    [7] => Pear
    [8] => Fig
)

Fruits array modified:
Array
(
    [0] => Apple
    [] => Banana
    [G] => Grape
    [7] => Pear
    [8] => Fig
    [1] => Orange
)

The behavior of the $fruits array is very interesting. Review it carefully.

Array Related Built-in Functions

PHP offers a number of interesting built-in functions to work with arrays:

  • array_combine() - Combines two arrays into a new array with the first array as keys and the second as values.
  • array_count_values() - Counts the frequencies of values in an array and returns them as an array.
  • array_key_exists() - Searches for a key in an array.
  • array_keys() - Returns an array with all keys of an array.
  • array_search() - Searches for a value in an array.
  • array_values() - Returns an array with all values of an array.
  • ksort() - Sorts an array by keys.
  • sort() - Sorts an array by values.

PHP also offers special loop statements to iterate over arrays:

foreach($myArray as $value) {}
foreach($myArray as $key=>$value) {}

Here is a simple script with a "foreach" statement:

<?php # ArrayLoop.php
# Copyright (c) 2003 by Dr. Herong Yang
# 
   print "\nLibrary hours:\n";
   $libraryHours = array(
      'Monday - Friday'=>'09:00 - 21:00', 
      'Saturday'=>'09:00 - 17:00', 
      'Sunday'=>'closed');
   foreach($libraryHours as $day=>$hours) {
      print "   $day: $hours\n";
   }
?>

Here is the output:

Library hours:
   Monday - Friday: 09:00 - 21:00
   Saturday: 09:00 - 17:00
   Sunday: closed

Conclusion

  • PHP's array is easy to use. But mixing integer indexed array with associate map is kind of confusing.

Part:   1  2 

Dr. Herong Yang, updated in 2006
PHP Tutorials - Herong's Tutorial Notes - Arrays