eHow launches Android app: Get the best of eHow on the go.

How To

How to Use an Array in PHP

Member
By Mike
User-Submitted Article
(0 Ratings)

Arrays are an important part of every programming language and PHP is no different. They allow you to store multiple values into a single variable. This is accomplished by being able to index the array either with a number or a key value. In this tutorial you will see all of the ways on how to use arrays in PHP.

Difficulty: Easy
Instructions
  1. Step 1

    The first step is to how you define an array. To define an array you can use the following:
    $statenames=array('NJ','PA','NY','CA','TX')
    This line of code says that the variable $statenames is an array (as noted by the keyowrd "array") and that we are assigning values to it. If you want to print out a specific item in this array you could write:
    echo $statenames[0]
    This would print 'NJ'. The zero is the index of the array and all arrays always start at zero up through the total number of items in the array minus 1. In our example here, we have 5 items in the array, therefore the indexs go from 0 through 4.

  2. Step 2

    Instead of indexes you can use key value pairs. Our above array can be written as:
    $statenames=array('mystate'=>'NJ','neighbor'=>'PA','bigapple'=>'NY')
    If you want to retrieve the value of 'bigapple' you would write:
    echo $statenames['bigapple']

    That would display 'NY'.

  3. Step 3

    To modify an element within an array you can do the following for the first step:
    $statenames[0]='NH'
    This changes element zero from NJ to NH
    For our example in step 2 you would write:
    $statenames['neighbor']='DE'
    This changes the value from PA to DE.

Tips & Warnings
  • This should be plenty to get you started :)

Comments  

tomglander said

Flag This Comment

on 7/19/2009 Well, now I understand better what an array is. Good explanation. Reminds me of programming class, except better explanations. Good work!

Post a Comment

Post a Comment
  • Have you done this? Click here to let us know.
I Did This

Related Ads

Tags
Computers
Alexia Petrakos,

Meet Alexia Petrakos eHow's Computers Expert.

Get Free Computers Newsletters

Copyright © 1999-2009 eHow, Inc. Use of this web site constitutes acceptance of the eHow Terms of Use and Privacy Policy.   en-US Portions of this page are modifications based on work created and shared by Google and used according to terms described in the Creative Commons 3.0 Attribution License.

eHow Computers
eHow_eHow Technology and Electronics