Welcome to Dream.In.Code
Getting Help is Easy!

Join 117,543 Programmers for FREE! Ask your question and get quick answers from experts. There are 1,728 online right now! We've got more than 500 tutorials and 2,000 snippets. Join and find out why Dream.In.Code is the #1 programming help community on the internet! Registration is fast and FREE... Join Now!



Introduction: Arrays

 
Reply to this topicStart new topic

> Introduction: Arrays, Arrays

niallj
Group Icon



post 25 Feb, 2005 - 11:16 AM
Post #1


PHP Basics :: Arrays

If you're a complete beginner and your exposure to PHP is none, then I would reccomend that you read my previous tutorial, PHP Basics :: Introduction and Scalars before proceeding to this section on arrays, as it contains some general information about PHP code as well as talking about PHP's most basic type of variable.

So for those of you who were here last time, wink2.gif, you should remember before you proceed to this tutorial what a scalar variable is, how they are represented in PHP syntax, how to assign data to them and how to print data. If you don't it would probably be beneficial to you to revisit PHP Basics :: Introduction and Scalars.

Scalar variables we have learnt are capable of holding a piece of data, be that a string, a number, a true of false value, or a resource identifier, which I promise we will come to in a further tutorial wink2.gif. But what about if we want to associate or group data together inside one variable? If you want to be able to hold 100 numbers for example, can you imagine PHP files like:

CODE

<?php
$numberOne= 55;
$numberTwo= 67;
$numberThree= 428;
//and so on upto
$numberOneHundred= 943;
?>


For one I don't think PHP would be as popular as it is if the above were necessary. Instead some kind programmer gave us the array. Remember that word- arrays are your friend smile.gif. What is this magical array though? It is essentially a scalar with many parts. Imagine for example that a scalar variable is a large box, in which you can put your data. Under the same analogy the array becomes one of those fancy tool boxes with many compartments and sub boxes inside it. You can now fit many pieces of data inside your single box. And like any normal scalar an array item can hold a string, number, true or false value or a resource identifier. Clever eh?

The way to access these individual pieces of data, referred to as elements, within your array is by indexing. Arrays can be indexed by numbers or strings in PHP. It is important to note that along with many other languages, PHP begins its numeric array indexing at the number 0, as opposed to the number 1 where conventional counting would begin. The name of the array is just like a scalar, but it is then followed by this syntax: [INDEX]; for example, $array[0] refers to the first numerically indexed element. The following example shows how to assign array sections and get the data out of them again.

CODE

<?php
//Assign the data into the array elements
//Note that they are assigned like scalars:- no declaration is necessary before definition
$myArray[0]= "The first element, numerically indexed"; //assignment by numeric index
$myArray[1]="The second element, numerically indexed"; //second assignment by numeric index
$myArray["string"]= "Another array element, indexed by a string"; //an assignment by string index

//Print the data from them
echo $myArray[0]."<br />\n";
echo $myArray[1]."<br />\n";
echo $myArray["string"]."<br />\n";

//Modify them
//Note that the redefinition syntax is identical to that of the definition syntax
$myArray[0]= "The first element, redefined.";
$myArray[1]= "The second element, redefined.";
$myArray["string"]= "The third element, redefined";

//And again print the data from them
//Print the data from them
echo $myArray[0]."<br />\n";
echo $myArray[1]."<br />\n";
echo $myArray["string"]."<br />\n";

?>


You may still be wondering why arrays are so useful. Why would you want to group a lot of scalars together like that? The answer is that as you progress in PHP, you'll encounter situations where a lot of data needs to be assigned to one place and then made easily searchable and indexable. For example, when retrieving lots of records from a database, an array can store them all under one name, and they can be searched through by numerical index. Another example is being able to read a file into an array, with each element holding a new line.

The syntax we have shown above is effective and perfectly correct, but a little cluttered. The example below introduces the array() function. The pattern of the arguments is a little complex, but it's easily remembered once learned.

Note:- Although I have referred to array() as a function, (we'll learn more about these later but for now just think of them as a block of code that we can't see), it's actually a language construct written specifically for definining arrays.

CODE

<?php
/* The syntax below will create an array automatically indexed by numbers.
  For example, the 0 will be placed in element 0, the 1 will be placed in elemenmt 1 and so on.
  Unless an index is explicitly specified, PHP will assign a numeric index equal to the highest current numeric index plus one.*/
$myArray= array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); //Assigns an array with automatic numeric indices

/* If this isn't what you want, you can explicitly define an index, numeric or text with the => operator like so */

$mySecondArray= array("red" => "#FF0000", "green" => "#00FF00", "blue" => "#0000FF"); /*This creates an array with the indicies "red" "green" and "blue", where each index contains the hexadecimal RGB code of that color. */

/* Or you can assign a mixture of string indices and numeric indices. If you explicitly define a numeric index, any automatic assignments will continue from that number, not from the previously automatically assigned index */
$myThirdArray= array("Element", "index" => "anotherElement", 3 => "elementThree", "elementFour");
?>


The first two uses of array() are pretty clear I would imagine, but the third can be a bit tricky, so I'll explain. The first piece of data we pass to it is just a string. No index is defined so it is automatically given index 0. The next piece provides a string that should be indexed by the string "index". The third piece of data says that the element at index 3 should be the string provided, and because of the explicit numeric declaration, PHP's internal variables that keep track of our position in the numeric indices are set to three. This means that our next piece of data, a string with no explicit index is assigned the index 4, which is one greater than the previous numeric index. This means that the array generated by the final array function will look a little like this:

CODE

Array $myThirdArray {
0 => "Element";
"index" => "anotherElement";
3 => "elementThree";
4 => "elementFour";
}


So now we can create arrays, and access the data within them. At the time of posting there are over fifty functions for working with arrays in PHP- clearly it would be impractical to try and explain them all here. I will explain the use of a few, and if you find yourself wanting to perform a task other than the ones that they provide, take a look at the php manual, at http://www.php.net. Type array in the search box on the right, ensure that function list is specified as the search location and click search. You should find a page detailing all the array functions, and their usage.

Before I teach you those array functions though, I'm going to cheat a little and break my structure. !. I did want to break all the features of PHP into separate tutorials, however that would be rather disjointed and useless. biggrin.gif. So therefore, I'm going to introduce a loop structure, to allow us to get through all the elements of our array. A loop does exactly what it sounds like- performs a certain task many times, looping rather like a repeated music playlist. And I'm not breaking my structure too much, because this loop is designed especially for arrays- wink2.gif

It's called the foreach loop. It, fairly predictably, performs a certain task for each element of an array. The example below shows how it works.

CODE

<?php
    $array= array("element", "cheese", "foo", "bar", "php", "rocks!", "=D"); //make an array
    foreach($array as $element){ //for every element in the array $array, make a scalar called $element and give it the value of the array element that we are currently at
 echo $element."<br />"; //then print it
    }
?>


The example above will produce this:

CODE

element
cheese
foo
bar
php
rocks
=D


Easy eh?

That's all I want to say about arrays for the present, although later on I'll include some more details about searching and sorting them. Look out for the next tutorial, PHP Basics: Operators.

Btw, as before don't hesitate to notify me about any error, and I will rectify it. smile.gif
Go to the top of the page
+Quote Post


Register to Make This Ad Go Away!

skyhawk133
Group Icon



post 25 Feb, 2005 - 02:45 PM
Post #2
Once again, an excellent tutorial!!! Thanks niallj
Go to the top of the page
+Quote Post


Reply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 

Lo-Fi Version Time is now: 10/7/08 05:45PM

Live Help!

Tutorials

Programming

Web Development

Reference Sheets

Code Snippets

Bye Bye Ads

Free DIC T-Shirt

T-Shirt Example

Related Sites

Monthly Drawing

Thumb Drive

Partners

Top Contributors

Top 10 Kudos This Month