SunQuest
 
       Programming Basics
  Home arrow Programming Basics arrow An Overview of Arrays in PHP
Moblin
Try It Free
Codewalker Forums 
  Tutorials  
Database Articles  
Miscellaneous  
Navigation Usability  
PEAR Articles  
Programming Basics  
Server Administration  
XML Tutorials  
  Reviews  
Database Book Reviews  
Linux Book Reviews  
Miscellaneous Reviews  
PHP Book Reviews  
PHP Software Reviews  
Server Admin Reviews  
SQL Tool Reviews  
  Code Gallery  
Content Management Code  
Contest Code  
Counters Code  
Database Code  
Date Time Code  
Discussion Board Code  
Email Code  
File Manipulation Code  
GUI Code  
Link Farm Code  
Miscellaneous Code  
Search Code  
Site Navigation Code  
User Management Code  
Forums Sitemap 
Dedicated Servers  
Download TestComplete 
JMSL Numerical Library 
IBM® developerWorks
Weekly Newsletter 
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PROGRAMMING BASICS

An Overview of Arrays in PHP
By: Matt Wade
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 2 stars2 stars2 stars2 stars2 stars / 7
    2002-05-03

    Table of Contents:

    Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
    Try It Free
     
    ADVERTISEMENT

    Get inside! Sample the range of functionality easily built with JMSL Library for Time Series Data Analysis, Heat Maps, Portfolio Optimization, Monte Carlo Simulation, Stock Price Charting and more. Download Now!

    In this article I will explain arrays and how they are used in PHP.

    The PHP Manual defines an array in PHP as an ordered map. Personally, I don't like this definition. I will define an array in PHP as a collection of variables, which I think is a little more descriptive. In most languages, at least the ones I am familiar with, the variables in this collection must all be of the same type. Not so in PHP! This is because of PHP's Type Juggling. I'm not going to go into great detail about Type Juggling, but basically it means that you don't declare a variable as a certain type. The context in which the variable is used determines its type.

    So, how do you assign values to arrays? The exact same way as you would any other variable, except that you specify which element of the array you wish to work with. One important thing to note is that, by default, arrays start numbering their elements at zero. Check this out:

    <?php
    $array
    [0] = 3;
    $array[1] = 6;
    $array[2] = 2;
    ?>

    A cool feature of PHP is the ability to use associative arrays. Associative arrays give you the ability to name your array's keys. So, instead of having $array[0] and $array[1] you can have $array['something'] and $array['anotherthing'].

    So what's the big deal? Why would I want to use arrays rather than just regular old variables? Imagine this: You are working with customer's names. You have 5 of them that you continually need to echo out. With regular variables, you would do it like this:

    <?php
    echo "$customer1&lt;BR&gt;\n";
    echo 
    "$customer2&lt;BR&gt;\n";
    echo 
    "$customer3&lt;BR&gt;\n";
    echo 
    "$customer4&lt;BR&gt;\n";
    echo 
    "$customer5&lt;BR&gt;\n";
    ?>

    Pretty long winded. Imagine doing that with 100 customers. Or 1000. With arrays, you can use a foreach loop. What a foreach loop does is loop as many times as you have elements in an array. Suppose you had an array called $customer that contained your customer names. Check this out:

    <?php
    foreach($customer as $value) {
       echo 
    "$value&lt;BR&gt;\n";
    }
    ?>

    Now how easy is that? That code will not change if you have 100 or 1000 customers. That's the beauty of arrays.

    Ok, that clues you in on some simple arrays. What about multi-dimensional arrays? What are they? Let's take a look at a two-dimensional array as an example. Say you are dealing with selling books. You want to place the names and prices of these books into an array. What you would want to do is create an array where each element is an array. Sound confusing? It really isn't. Take a look at this example:

    <?php
    $books 
    = array(0=>array('name'='A Book','price'=>9.99),1=>array('name'='Another Book','price'=>17.99));
    ?>

    Now, here are a couple ways to access that data in our two-dimensional array:

    <?php
    echo $books[0]['name'];
    echo 
    $books[1]['price'];
    $books[0]['price'] = 12.99;

    foreach(
    $books as $onebook) {
       echo 
    $onebook['name'] . " sells for $"$onebook['price'] . "&lt;BR&gt;\n";
    }
    ?>

    There you have it. A simple introduction to arrays in PHP. I hope it was helpful to you. For more info, check out the PHP Manual. There are a whole bunch of functions in there that can be used with arrays.


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

    More Programming Basics Articles
    More By Matt Wade

     

    IBM® developerWorks developerWorks - FREE Tools!


    IBM DB2 Deep Compression ROI Tool

    The IBM DB2 Deep Compression ROI tool is designed for DBA’s and IT management personnel to perform a clinical analysis of the cost savings gained from the Storage Optimization feature of DB2 9 for Linux, UNIX and Windows. The feature, also known as Deep Compression, compresses data that lies within a database by up to 80% at times.
    FREE! Go There Now!


    NEW! Driving Business Success with Rational Process Library

    Join this webcast, to learn how the Rational Process Library can help with compliance issues, drive process improvement, and assist in service-oriented architecture (SOA) or Agile development. We will take a peek into the Rational Process Library with content around software and systems engineering (including RUP), operations and systems management, program and portfolio management, and asset and SOA governance.
    FREE! Go There Now!


    NEW! BlammoSplat: Build a community Web site of OpenLaszlo animations, Part 3: The community animation

    Learn to enable users to both rate existing animations and to combine existing animations into new snippets. This is the third in a series of three tutorials that chronicle the building of a site that enables collaborative discussion and animation building using Domino and OpenLaszlo.
    FREE! Go There Now!


    NEW! Develop Systems Software Assets with IBM Rational Asset Manager

    Join us for this on demand webcast to learn about developing complex systems more quickly and efficiently. We'll cover market drivers for developing, governing and reusing systems software assets and how you can develop system software assets with Rational Asset Manager.
    FREE! Go There Now!


    NEW! Evaluate Rational Business Developer V7.1

    Visit IBM developerWorks to download a free trial version of IBM Rational Business Developer V7.1. Rational Business Developer offers rapid and simplified development of business applications and services through Enterprise Generation Language (EGL) tools, generating Java or mainframe solutions while shielding developers from technical complexities.
    FREE! Go There Now!


    NEW! Improve your build process with IBM Rational Build Forge, Part 2: Automate builds for a real-world Tomcat project

    Learn how Rational Build Forge can extend a simple compile and package build process by adding customization and deployment capability. Go from a manual method to automating: checking for code changes; getting the latest source; compiling and packaging; customizing; copying to and restarting a deployment server; and sending e-mail notification that a new version is available.
    FREE! Go There Now!


    NEW! Rational Testing eKits

    Discover how Rational tools and best practices for testing can make your job easier. The new Rational Testing eKits provide you with valuable resources – including demos, webcasts, tutorials, and articles – that help you address your specific testing needs across the software lifecycle. Five new eKits are available covering the topics of Requirements and Test Management, Functional Testing, Performance Testing, Code Quality and Embedded Systems, and SOA and Web Services Testing.
    FREE! Go There Now!


    NEW! Successful Change and Release Management for .NET

    Join this webcast to discover the key requirements for successful change and release management. Learn how to extend your .NET environment to improve productivity and collaboration, and address core problems afflicting team development. In this webcast, we’ll review typical challenges faced by customers and how to resolve them with the IBM Rational Change and Release Management solution, including Rational ClearCase, Rational ClearQuest and Rational Build Forge. Replay is available for 9 months.
    FREE! Go There Now!


    NEW! Trial download: IBM Rational Functional Tester V7.0.1

    Get a free trial download of the latest version of IBM Rational Functional Tester V7.0.1. Rational Functional Tester is an automated functional and regression testing solution for QA teams concerned with the quality of their Java, Microsoft Visual Studio .NET, and Web-based applications.
    FREE! Go There Now!


    Refresh! IBM Rational Systems Development Solution eKit

    With IBM Rational Systems Development Solution, you can deliver products faster with higher quality. Within this kit, Read the “Model Driven Systems Development” white paper to see how to improve product quality and communication. Then check out the rest of the e-Kit to learn more about important topics that can affect the success of any software project through customer examples, tutorials, informative Webcasts, and best practices for designing, building and managing systems. From start to finish, at every stage in your projects, Rational Systems Development Solution can help your company reach its full potential.
    FREE! Go There Now!



    All FREE IBM® developerWorks Tools!

    PROGRAMMING BASICS ARTICLES

    - Loops and PHP Decision Making
    - Operators, Conditionals, and PHP Decision-Ma...
    - PHP Decision-Making
    - Coding
    - Server Statistics
    - Looping in PHP
    - Cookies in PHP
    - Working with text files
    - Beginning Object Oriented Programming in PHP
    - A Tour of Decision Making Structures in PHP
    - PHP Strings Primer
    - PHP Control Structures
    - Intro to Vim
    - Reading Directorys with PHP
    - An Overview of Arrays in PHP


    Iron Speed




    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 5 hosted by Hostway