Basics
Creating a Document
Head and Body Elements
Formatting Text
Creating Lists
Embedding Images
URLs Explained
Linking to Documents
Creating Tables
Forms Form Basics
Input and Textarea
Select Lists
Frames Framesets
The Frame Element
Nested Framesets
Targetting Frames
Inline Frames
Tips and Tricks Meta Tags
Transition Effects
HTML Generators Create a Document
Create a List
Create a Table
HTML
Basics
Implementing CSS
CSS Syntax
Pseudo Classes/Elements
CSS Classes
CSS Properties Font Properties
Color and Background
Text Properties
Border Properties
Margins and Padding
Size and Position
Tips and Tricks Menu Buttons
Special Effects
CSS
Basics
Running a Script
Variables
Expressions and Operators
Objects.Properties.Methods
The Date Object
Strings
Regular Expressions
Defining RegExp Patterns
Branches and Conditions
Loops
Arrays Array Basics
Array Methods
Sorting Arrays

User-Defined Functions
Cookies
Windows
Frames
Tips and Tricks Image Replacement
Using Includes
Form Validation
Debugging
JavaScript
Basics
Creating a Script
Running a Script
Variables
Expressions and Operators
Strings Strings Basics
Strings and Substrings
Replacing Substrings
Regular Expressions
Branches and Conditions
Loops
Arrays Array Basics
Array Functions
Sorting Arrays
User-Defined Functions
Include and Require
Uploading Files
File Functions
Session Variables
Tips and Tricks Page Templates
Form Reply Scripts
Form Validation
JavaScript to PHP
PHP
Basics
Create and Drop
Show and Describe
Insert, Update and Delete
Querying
Join Queries
Functions
Table Locking
PHP/MySQL Functions Accessing a Database
Querying with PHP
Create and Drop with PHP
Insert and Update with PHP
Frequently Used Functions MySQL
Basics
Layout and Navigation
Page Content Style
Web Page Copy
Graphics and Animation
HTML Forms
Accessibility
Legal Requirements
MySQL

Home > PHP > Arraysprinter version

PHP Arrays

An array is an ordered set of variables where each variable is known as an element. Arrays in PHP can hold integers, floats, Booleans, strings, objects, other arrays as well as values of mixed type.

Arrays in PHP can be numbered or associative.



Creating an Array

The array() construct is used to create an array.

A Numbered Array

The index for the first element in an array is 0 by default but it can start at any numeric value you choose.

Example of a Numbered array
<?php
    $names = array ("Tom", "Dick", "Harry");

    // Print out the second element in the array

    echo ($names[1]);
?>


To start the array index at a numeric value other than the default 0 or if you wish to leave gaps in the array it can be done as below.

Example of a Numbered array with Gaps
<?php
    /* This starts the array at element 1 and
    leaves out evenly numbered elements */

    $names = array (1=>"Tom", 3=>"Dick", 5=>"Harry");
?>


An empty array can be created and values added later in the script using the bracket syntax. If an index isn't supplied inside the bracket then PHP automatically assigns the highest current index + 1.

If an index is supplied inside the bracket then it will overwrite the current value, if it exists, with the new value.

Creating an Empty array then Updating it
<?php
    $names = array ();

    /* Later on in the script
    the values can be added */

    $names[] = "Tom";
    $names[] = "Dick";
    $names[] = "Harry";
?>


An Associative array

This is similar in form to a numbered array except that the elements are accessed by string indexes, called keys.

Example of an Associative array
<?php
    $pages = array (     
    "html"=>"HTML Tutorial",
    "css"=>"CSS Tutorial",
    "php"=>"PHP Tutorial");

    /* This will print out the
    string "CSS Tutorial" */

    echo ($pages["css"]);
?>


A Heterogeneous array

PHP allows values of different types to be stored in array as shown below.

Example of a Heterogeneous array
<?php
    $details = array ("Tom", 40, "Main Street", 20.4, true);
?>


Multidimensional arrays

A multidimensional array is an array that holds other array(s). This can be to be whatever depth is required.

Example of a Two Dimensional array
<?php
    $details = array (array("Tom", "Dick", "Harry"),
    array ("Main Street", "Brick Lane", "Holme Road"));

    // This will print out Brick Lane

    echo ($details[1][1]);
?>


The foreach Loop

The foreach statement is specially designed for use with arrays - both numbered and associative. The loop executes once for each element in the array and takes two forms.

  1. The first form assigns the value in each element to a variable identified with the as keyword.
  2. The second form assigns both the key and the value in each element to a pair of variables identified with the as keyword.


foreach Loop Using the First Form
<?php
    $list_of_names = array("Tom", "Dick", "Harry");

    foreach ($list_of_names as $name)
    {
        echo ($name.', ');
    }

    // This will print out Tom, Dick, Harry
?>


foreach Loop Using the Second Form
<?php
    $details = array("Tom" => 40, "Dick" => 36, "Harry" => 25);

    foreach ($details as $name => $age)
    {
        echo ($name.' is aged '.$age.'<br>');
    }

    /* This will print out
    Tom is aged 40
    Dick is aged 36
    Harry is aged 25
    */
?>


If the second form is used with a numbered array then the index is assigned to the variable identified with the key.

Array Pointers

Before foreach was introduced in PHP4, array pointers were used with while loops to iterate through arrays.

Since foreach is so much easier to use, the use of array pointers are not covered here.

Previous - PHP loops Previous - Loops     Next - Array Functions Next - PHP array functions


Privacy | Terms | Contact | Links | Sitemap | RSS Feeds RSS and JavaScript Feeds
©2010 www.webdesignworkmate.co.uk all rights reserved 
Design and Production by smallbizonline website design © 2000-2010
Valid HTML 4.01! Level Double-A conformance icon, W3C-WAI Web Content Accessibility Guidelines 1.0Valid CSS!
PHPBasicsCreating a ScriptRunning a ScriptVariablesExpressions and OperatorsStringsStrings and SubstringsReplacing SubstringsRegular ExpressionsBranches and ConditionsLoopsPHP arraysArraysArray FunctionsSorting ArraysUser-Defined FunctionsInclude and RequireUploading FilesFile FunctionsSession Variables
Recommended Reading
PHP and MySQL web development

programming PHP

PHP cookbook
Tips and TricksPage TemplatesForm Reply ScriptsForm ValidationJavaScript to PHP
Got any PHP Tips?
Send me your tip and if it's suitable I'll put it on the site, credit it to you and add a link back to your site.