PHP Tutorials - Herong's Tutorial Examples
Dr. Herong Yang, Version 3.00

Array Related Built-in Functions

This section provides a tutorial example on how to create arrays in different ways.

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.
  • array_push() - Treats the array like a stack and pushes extra values to the end of the stack.
  • array_pop() - Treats the array like a stack and pops the last value from the stack.
  • 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

Last update: 2005.

Sections in This Chapter

What Is an Array?

Creating Arrays - Examples

Array Related Built-in Functions

Dr. Herong Yang, updated in 2009
Array Related Built-in Functions