Detailed Guide On Arrays In PHP
Submitted by haroon on Tue, 2007-02-06 20:22. :: PHP
Detailed Guide On Arrays In PHPGood Day! Here is yet another article of Fast PHP Articles Series. Today we are going to discuss ARRAYS. We will learn its syntax, its different types, the different built-in array functions that help to perform different tasks related to arrays quickly and different practical examples explaining the use of arrays in PHP. By the end of this article you should be able to: - Define Arrays - Write basic as well as complex php code using Arrays. But before we discuss arrays let me tell you a very interesting story. I have a DVD shop near my office that keep a very good collection of English movies. You can find movies on almost all genres e.g action movies, horror movies, romantic movies (hhhhh - ‘deep breath’), dramas, stage plays, religious movies and so on…. The shop-owner is not a very educated person but still he is able to manage the 20,000 plus DVDs very easily and he can take out the movie as soon as you say its name… hmm, the point is that how does he do that? Well, I have analyzed his strategy and let me disclose this big secret to oraganize bunch of items with a special method to handle them easily. He has categorized all the DVDs into different genres as we discussed above and also has given special IDs / codes / numbers to different shelves in his shop. He keeps the related movies in the same shelves. Each shelf is labeled after the category name e.g Romantic Movies, Horror Movies etc etc… Each DVD has a unique ID that can be used to track that DVD. When a customer asks for a movie say Double Team, he quickly moves to the shelf labeled as Action Movies, then to the ROW labled as ‘D’ which means movies names starting with ‘D’ and then quickly reaches to the sequence of ‘D’ followed by ‘O’ and gets to the DOUBLE TEAM movie. And he memorizes the IDs of famous DVDs so when you ask him he will tell you pick the DVD # xxxx from shelf labeled by THIS NAME and you can directly pick it from there. And all this is done so quickly that it seems like magic to get a specific DVD from a huge collection so quickly. So if you ever start to run a DVD shop then do the following to ORGANIZE YOUR DVDs: a) Keep the similar DVDs in the same shelf. Let’s mug the moral of this story and move back to the computer world. In programming sometimes you have to handle with different related values which are bound together in different ways. For example Names Of Top Five Students, Models Of Porsche Cars, Variables Submitted From A Form and so on. In such conditions you need to organize your code and logic to handle similar type of data efficiently and quickly. For this purpose you can use the logic of DVDs seller by: 1) Organizing Data into different bounded-together categories. There could be different techniques to do this and one of them is ARRAYS. Raw Definition Of Arrays: A box that helps you to keep the similar data / data of same interest together for better organizing and processing Proper Array Definition:“Collection of different variables under the same label to keep values organized and easily accessible for processing” Yeah, it’s my own definition of arrays and I keep the right to define anything in my own words as long as the core concept is correct and you can understand what I am talking about. Though some also define arrays as “it’s kind of variable that contains more variables in itself”. Please remember that PHP handles normal variables and arrays in a slightly different way. Array Syntax:$arrayName = array (”value1″,”value2″,”value3″); We use $ sign to give an array name like we do for variables, after that an equal sign and then keyword ‘array’ that tells the parser that we are working with arrays and then different values within parenthesis and each value enclosed in double quotes separated by comma. PHP Example to define and print arrays:<?php The output of the above programme will be. Array Please note that we use print_r to print an array because you cannot print an array with echo or print function (both are used to display output) though you can use echo or print to display single items from the array e.g.: echo $Top3Sites[0]; //fastcreators.com Remember that the index number starts from 0 and not 1. Each value of the array get a unique ID which is known as INDEX NUMBER. The other way could be to define three different variables and then assign them values and use different statements to display them. It could be acceptable in case of three values for the sake of argument though will be rejected when we are dealing with fifty or hundred values. So arrays are more organized and can serve to collect the different values under the same label for quick processing. In the above example we defined and assigned values to the array in a single step though you can also do it as follows: <?php //assigning values $students[0] = "Haroon"; ?> Types Of Arrays:There are three different types of arrays in PHP: a) Numeric Array: An array with a numeric ID key. Now lets discuss different types of arrays in details. Numeric Arrays: Numeric arrays use integer / numbers as their index number to identify each item of the array. The example we discussed above are numeric arrays as they have integer values as index numbers for each item. <?php print_r($colours); /* Array In the above output you can see the index numbers for white, black and blue are 0,1,2 respectively which are numeric values and hence we call such arrays numeric arrays. Associative Arrays:Sometimes it’s better to use the index name instead of index number for example if you want to save three students' names and numbers so your best option will be to use each student’s name as index value for the array and his numbers as the values, behold on the example below,
<?php When you submit a form using POST or GET method you get a similar associative array on the receiving page that contains the name of each form field as array index and its value as index value. Try to make a HTML form with some fields and post it and on the receiving page print the global arrays like print_r($_POST); and you will see the associative array. Associative Arrays are more easy to handle and to process information especially dealing with complex form submission and dynamic values from database etc. Multidimensional Arrays:A multidimensional array can contain arrays within itself and the sub arrays contain more arrays within them. Let's move to a real world example to understand the concept of multidimensional arrays: David has two sons Richie and Mason. Richie has two daugters Sue and Natasha while Mason has three daughters Nichole, Salma and Amber. Now they family tree is as follows: If we want to display David’s family tree with a multidimensional array in PHP then we can define an array as below: $david = array “Mason”=>array ); This is how you can use multidimensional arrays to organize data. Try to submit an array of form fields and then print the global array to check the output, you will get the global array as multidimensional array that will contain more sub arrays. FOREACH LOOP: If you remember in my last article about “Loops In PHP” I had left the FOREACH LOOP to be discussed later and now the time has come to discuss it. Foreach loop is used for arrays to take each next value from array and perform whatever action is required on it. The basic syntax of a foreach loop is as below: FOREACH Syntax:foreach ( $arrayname as $temporaryVarName ) { // foreach loop body Let’s write a programme using a foreach loop to understand its working in depth: <?php In the above code the $std_name works as a temporary variable to get each value of array. On every loop-run the next available value of the array overwrite the existing value of the $std_name and then $std_namepoints to the current fetched value. So it’s just like walking through your array values one by one. The output of the above code will be: david as we are using \n (line feed) to display each name on the next line. The foreach loop terminates when there is no value available next that is it reaches the last value of the array which is NAYYAR in our case. You can break the loop anytime using break statement if required (we have discussed break statement in the DECISION MAKING USING SWITCH IN PHP). For example if you want to break the loop if the name is julie then you can include an IF statement in the above code as below: <?php Important Array Functions:1) Save print_r function’s output: we have previously used print_r to display the array values, though we can add an extra argument to print_r and save its output to a variable e.g.:
<?php The print_r will display the array itself if you will not use TRUE - the second argument however it will store its output in the variable if the TRUE is provided. 2) How to find the size of an Array? Size of an array means how many values an array contains… if you want to find the number of values of an array you can use the COUNT function as follows: <?php The above programme will display 3 because we have three elements in the array. 3) var_dump Function: There is a similar function to print_r(), which is var_dump(). It does largely the same thing, but a) prints out sizes of variables, For example, altering the first script to use var_dump() rather than print_r() would give the following output: array(3) { In there you can see var_dump() has told us that the array has three values, and also prints out the lengths of each of the strings. For teaching purposes, var_dump() is better as it shows the variable sizes, however you will probably want to use print_r() in your own work. 4) var_export Function: Also, there is the function var_export(), which is similar to both var_dump() and print_r(). The key difference with var_export(), however, is that it prints out variable information in a style that can be used as PHP code. For example, if we had use var_export() instead of print_r() in the test script, it would have output the following: array ( Note there is an extra comma after the last element, however this is ignored by PHP and you can copy and paste that information directly into your own scripts, like this: <?php 5) array_shift Function: The array_shift function removes the first element of an array from the array and stores it in the receiving variable. For example if I want to remove Apples from the array used in previous programmes and store it in a different variable then I can write a programme as below: <?php It is a very handy function if you have a multidimensional array posted from a form and you want to fetch the sub-array from the main array. But remember when you fetch out a sub-array from the main array using array_shift then the receiving variables ($fruit in previous) will not be a normal variable but an array. I will also suggest you to study three other useful functions related to array_shift on PHP Official Manual at array_unshift PHP offers a very long list of different useful array functions that you can find at PHP OFFICIAL MANUAL. One thing I want to mention here is that the foreach loop is not the only way to process arrays - you can do it using other loops e.g FOR LOOP or list() and each() functions. To process an array through you will need to find the total number of the values in the array, i.e the size of array as below: <?php This will work fine for numeric arrays which have integer values as index-numbers but this doesn’t fit associative arrays. Process Arrays with LIST() function:PHP offers the LIST() function that can be used to go through array values easily and quickly as below: <?php List() is a function that does the opposite of array() - it takes an array, and converts it into individual variables. Each() takes an array as its parameter, and returns the current key and value in that array before advancing the array cursor. “Array cursor” is the technical term for the element of an array that is currently being read. All arrays have a cursor, and you can freely move it around - it is used in the while loop above, where we need to iterate through an array. To start with, each() will return the first element, then the second element, then the third, and so on, until it finds there are no elements left, in which case it will return false and end the loop. The meaning of that first line is “get the current element in the array, and assign its key to $var and its value to $val, then advance the array cursor". Get both index and value of array element: If you want to read the index-name as well as its value for each array element then you can use foreach loop as follows: <?php It is very handy when you deal with associative arrays. Arrays are a very deep topic and it has a lot more to discuss and even I can easily write a complete book on arrays only. But the aim of this article is to give you very sound understanding of arrays and different methods to store and process information in arrays. However if you have any specific question about arrays please feel free to email me or comment on this article. It’s a long article so there could be a few typos if you find any please report to me so that I can fix it. Till we meet again keep practicing and take care… - Haroon Ahmad Other Articles Of This Series:FAST PHP Tutorial (Part 1) login or register to post comments | email this page | view as pdf | printer-friendly version | | | | | | | | | | 306 reads
|
Recent comments
1 day 6 hours ago
1 day 13 hours ago
1 day 19 hours ago
1 day 23 hours ago
3 days 6 hours ago
3 days 9 hours ago
6 days 13 hours ago
6 days 16 hours ago
1 week 4 hours ago
1 week 15 hours ago