PHP
  Home arrow PHP arrow An Introduction to Arrays
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
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? 
PHP

An Introduction to Arrays
By: Eric 'phpfreak' Rosebrock
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 4
    2003-04-18

    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
     
     
    ADVERTISEMENT


    In this article, Eric will denomonstrate the use of arrays in PHP. This article is mainly for beginner PHP programmers to give them a push in the right direction.

    What is an Array?

    Arrays can most easilly be described as an ordered list. An array is a list of scalar data (If you don't know what a scalar variable is, you should take a look at my first tutorial. Scalar data in arrays are called 'elements'.) that is 'indexed' (so to speek) with numeric or named keys. A 'key' is either a name or a number given to an element in an array as a reference (if a key is numeric, it is called a 'subscript').

    An Example of an Array

    <?php
    $six = 6;
    $arrayname = array("this is an element",5,$six);
    echo $arrayname[0]; //prints: this is an element
    echo $arrayname[1]; //prints: 5
    echo $arrayname[2]; //prints: 6
    ?>

    As you can see, elements in an array can be any type of scalar data (string, integer, double) and can also be other variables. In this example, the 'keys' are numeric (assigned automatically for you), so when echo'ing the elements, you use the array name followed by the subscript ($arrayname[subscript]). Notice that the subscript of the first element is zero? This will always be the case with numeric keys.

    Associative Arrays

    Associative arrays are arrays that use named keys that you assign to them. Lets look at a few examples...

    <?php
    $arrayone = array("key1" => "this is the first element.", "key2" => "this is the second element");
    $arraytwo = array(
        "key3" => "this is the first element of the second array",
        "key4" => "this is the second element of the second array",
    );
    echo $arrayone['key1']; //prints "this is the first element."
    echo $arraytwo['key3']; //prints "this is the first element of the second array"
    echo $arrayone['key2']; //prints "this is the second element"
    echo $arraytwo['key4']; //prints "this is the second element of the second array"
    ?>

    Now we're getting to where you know how to define an array (and an associative array), but you probably don't see how there useful yet. Well think of this, say you have a bakery that sells pies. You have 3 different flavors, and each flavor has a different price. lets make this example in php...

    <?php
    $bakery = array(
        "cherry" => "5.00",
        "apple" => "4.00",
        "other" => "2.00",
    );
    echo "cherry pie costs $bakery['cherry'], apple pie costs $bakery['apple'], and that other pie costs $bakery['other'].";
    ?>

    Ok, you've got an example of how to use arrays (a very basic example, grant me that). But what if you want to give more information on each pie? You now have the cost, but what if you wanted to add the number of pieces you get for that price, and if the pie was sugarless or not? One way is using mutlidimensional arrays.

    Multidimensional Arrays

    Think of multidimensional arrays as simply a list of arrays. This might seem confusing at first, but im sure with a few examples (and a few pies) you will get the big picture. Pick up your fork, its time to eat:

    <?php
    $bakery = array(
    "cherry" => array("5.00","2 pieces","sugar"),
    "apple" => array("4.00","3 pieces","sugar"),
    "other" => array("2.00","1 piece","sugar-free"),
    );
    echo "cherry pie costs ".$bakery['cherry'][0].", and you get ".$bakery['cherry'][1].".";
    //prints "cherry pie costs 5.00, and you get 2 pieces."
    echo "apple pie costs ".$bakery['apple'][0].", and you get ".$bakery['apple'][1].".";
    //prints "apple pie costs 4.00, and you get 3 pieces."
    echo "the other pie costs ".$bakery['other'][0].", but its ".$bakery['other'][2].".";
    //prints "the other pie costs 2.00, but its sugar-free.
    ?>

    Hopefully now you will be prepared to use arrays when you begin querying mysql databases, and performing other forms of intermediate to advanced data manipulation. If you've noticed, this 'tutorial' wasn't really a tutorial. I'm only trying to give you the basic idea of how to define and use these arrays, not give you all the information a person could possibly fathom. Hey, that might explain the whole "Introduction" word in the title.

    Related Functions

    array_change_key_case -- Returns an array with all string keys lowercased or uppercased
    array_chunk -- Split an array into chunks
    array_count_values -- Counts all the values of an array
    array_diff_assoc -- Computes the difference of arrays with additional index check
    array_diff -- Computes the difference of arrays
    array_fill -- Fill an array with values
    array_filter -- Filters elements of an array using a callback function
    array_flip -- Flip all the values of an array
    array_intersect_assoc -- Computes the intersection of arrays with additional index check
    array_intersect -- Computes the intersection of arrays
    array_key_exists -- Checks if the given key or index exists in the array
    array_keys -- Return all the keys of an array
    array_map -- Applies the callback to the elements of the given arrays
    array_merge_recursive -- Merge two or more arrays recursively
    array_merge -- Merge two or more arrays
    array_multisort -- Sort multiple or multi-dimensional arrays
    array_pad -- Pad array to the specified length with a value
    array_pop -- Pop the element off the end of array
    array_push -- Push one or more elements onto the end of array
    array_rand -- Pick one or more random entries out of an array
    array_reduce -- Iteratively reduce the array to a single value using a callback function
    array_reverse -- Return an array with elements in reverse order
    array_search -- Searches the array for a given value and returns the corresponding key if successful
    array_shift -- Shift an element off the beginning of array
    array_slice -- Extract a slice of the array
    array_splice -- Remove a portion of the array and replace it with something else
    array_sum -- Calculate the sum of values in an array.
    array_unique -- Removes duplicate values from an array
    array_unshift -- Prepend one or more elements to the beginning of array
    array_values -- Return all the values of an array
    array_walk -- Apply a user function to every member of an array
    array -- Create an array
    arsort -- Sort an array in reverse order and maintain index association
    asort -- Sort an array and maintain index association
    compact -- Create array containing variables and their values
    count -- Count elements in a variable
    current -- Return the current element in an array
    each -- Return the current key and value pair from an array and advance the array cursor
    end -- Set the internal pointer of an array to its last element
    extract -- Import variables into the current symbol table from an array
    in_array -- Return TRUE if a value exists in an array
    key -- Fetch a key from an associative array
    krsort -- Sort an array by key in reverse order
    ksort -- Sort an array by key
    list -- Assign variables as if they were an array
    natcasesort -- Sort an array using a case insensitive "natural order" algorithm
    natsort -- Sort an array using a "natural order" algorithm
    next -- Advance the internal array pointer of an array
    pos -- Get the current element from an array
    prev -- Rewind the internal array pointer
    range -- Create an array containing a range of elements
    reset -- Set the internal pointer of an array to its first element
    rsort -- Sort an array in reverse order
    shuffle -- Shuffle an array
    sizeof -- Get the number of elements in variable
    sort -- Sort an array
    uasort -- Sort an array with a user-defined comparison function and maintain index association
    uksort -- Sort an array by keys using a user-defined comparison function
    usort -- Sort an array by values using a user-defined comparison function


    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 PHP Articles
    More By Eric 'phpfreak' Rosebrock

     

    IBM® developerWorks developerWorks - FREE Tools!


    NEW! IBM – Taking Web 2.0 to Work

    David Barnes, Lead Evangelist for IBM Emerging Internet Technologies will discuss aspects of Web 2.0 that bring value to corporations, academia, and government. He'll also discuss IBM's vision around Web 2.0, including the importance of remixability and consumability. The discussion will culminate with examples of various IBM Software Group solutions you can use to get ahead of the Web 2.0 adoption curve.
    FREE! Go There Now!


    NEW! Addressing software-as-a-service challenges using Tivoli security and WebSphere solutions

    Building a software-as-a-service solution requires addressing a few key technical challenges. In this webcast, we'll focus on the role of IBM Tivoli Directory Server and WebSphere Portlet Factory in creating a Software as a Service solution. We will demonstrate how to use Tivoli Directory Server to prevent the user population of one tenant from accessing the virtual portal and portlet components of another tenant. We will also use the dynamic profile capability of WebSphere Portlet Factory to create multiple highly customized applications from one code base.
    FREE! Go There Now!


    NEW! Evaluate IBM Lotus Sametime Standard V8.0

    Visit IBM developerWorks to download a free trial of the latest release of IBM Lotus Sametime Standard V8.0. Lotus Sametime Standard V8.0 is a platform for unified communications and collaboration that combines security features with an extensible, open solution including integrated Voice over IP, geographic location awareness, mobile clients, and a robust Business Partner community offering telephony and video integration.
    FREE! Go There Now!


    NEW! Evaluate IBM Rational Developer for System i V7.1

    Download a free trial version of IBM Rational Developer for System i V7.1, which provides a complete development environment for traditional i5/OS application development. IBM Rational Developer for System i is a new eclipse-based workstation offering for i5/OS application development that provides a comprehensive Integrated Development Environment for edit/compile/debug of traditional RPG/COBOL/C/C++ i5/OS applications.
    FREE! Go There Now!


    NEW! IBM Enterprise Modernization Sandbox for System z

    IBM Enterprise Modernization solutions help organizations evolve core IT systems towards modern architectures and technologies—reducing the burden of maintenance and freeing up resources to develop new business requirements and capabilities. With the IBM Enterprise Modernization Sandbox for System z you can evaluate IBM Enterprise Modernization solutions focused on five key areas: Assets, Architectures, Skills, Processes and Infrastructures, and Investment. Each solution is based upon real customer experiences and offers a proven path to get you started with your modernization projects.
    FREE! Go There Now!


    NEW! Rational Talks to You: Manage RUP-based CMMI initiatives

    Join this Rational Talks to You teleconference on December 4 at 1:00 pm ET to discuss how Rational Method Composer can help meet your compliance objectives. Get your questions answered!
    FREE! Go There Now!


    NEW! Rational Talks to You: Scott Ambler on being agile in a global development environment

    Join this Rational Talks to You teleconference on December 6 at 1:00 pm ET to participate in an agile application development discussion and get your questions answered on using IBM Rational Method Composer in a distributed environment.Get your questions answered!
    FREE! Go There Now!


    NEW! The dirty dozen: preventing common application-level hack attacks

    As organizations have grown increasingly dependent on online software, the risk of malicious attacks has also become far more serious. Fortunately, well-governed organizations can protect their Web applications by injecting vulnerability assessments and ethical hacks into their software development and delivery processes. This paper describes 12 of the most common hacker attacks and provides basic rules that you can follow to help create more hack-resistant Web applications.
    FREE! Go There Now!


    NEW! Whitepaper: Achieving consistency between business process models and operational guides

    Explore how Rational and WebSphere software enable enterprise documentation in SOA environments. Specifically, a new integration between IBM WebSphere® Business Modeler and IBM Rational® Method Composer software can help technical writers more easily keep enterprise operations manuals in sync with changes that are made to business processes, resulting in more accurate and timely documentation that benefits the entire enterprise.
    FREE! Go There Now!


    NEW! Whitepaper: Delivering SOA solutions: service lifecycle management

    The unprecedented scope of a service-oriented architecture (SOA) initiative brings to the forefront a number of management and governance issues that were sidestepped in the past. The key to a successful SOA implementation is managing and governing activities throughout the entire SOA delivery lifecycle by ensuring that services conform to the needs of all of the business’s stakeholders. Learn how service lifecycle management allows the business to ensure that the process by which services are defined, created, tested, deployed, optimized and retired is manageable, repeatable and auditable.
    FREE! Go There Now!



    All FREE IBM® developerWorks Tools!

    PHP ARTICLES

    - Making Usage Statistics in PHP
    - Installing PHP under Windows: Further Config...
    - File Version Management in PHP
    - Statistical View of Data in a Clustered Bar ...
    - Creating a Multi-File Upload Script in PHP
    - Executing Microsoft SQL Server Stored Proced...
    - Code 10x More Efficiently Using Data Access ...
    - A Few Tips for Speeding Up PHP Code
    - The Modular Web Page
    - Quick E-Commerce with PHP and PayPal
    - Regression Testing With JMeter
    - Building an Iterator with PHP
    - PHP Frontend to ImageMagick
    - Using PEAR's mimeDecode Module
    - Incoming Mail and PHP







    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 2 Hosted by Hostway
    Stay green...Green IT