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<BR>\n"; echo "$customer2<BR>\n"; echo "$customer3<BR>\n"; echo "$customer4<BR>\n"; echo "$customer5<BR>\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<BR>\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'] . "<BR>\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
developerWorks - FREE Tools! |
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!
|
|
|
|
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!
|
|
|
|
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!
|
|
|
|
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!
|
|
|
|
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!
|
|
|
|
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!
|
|
|
|
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!
|
|
|
|
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!
|
|
|
|
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!
|
|
|
|
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! |