Hall of Famer's PHP Tutorials: Chapter 6 - PHP Arrays

Forum
Last Post
Threads / Messages

Hall of Famer

Administrator
Staff member
Administrator
Joined
Dec 15, 2008
Messages
4,564
Points
48
Location
United States
Mysidian Dollar
214,223
Chapter VI - PHP Arrays

In Chapter 5, you learned the basics of PHP functions. Now we are ready to move on to the study of some widely used PHP data types/structures. These aint as powerful as Java's, but will come in handy. I am sure you are quite familiar with playing with scalar variables like numbers and strings, so now it is about time to move on to vector variables. This chapter is about PHP arrays.

Arrays are very useful data type in any programming languages, they are a collection of elements with each element having its own identity. In PHP, array can behave both like a traditional array in Java/C#, and like a hashmap, which makes it more powerful than typical arrays from another programming language.

The tutorial will teach you how to create and manipulate arrays, and then introduce a few useful built-in PHP array functions. If you are not familiar with how to use functions, it may be a good time to go back to chapter 5 and read the function basics section.


1. Creating a numeric Array:
To create a numeric array, you typically use the array keyword with elements enclosed in parenthesis. Below is a standard way to declare arrays:

PHP:
$array1 = array();
$array2 = array(0, 1, 2, 3, 4);

The first array is an empty array, you simply declare the variable $array1 to be an array so functions/objects operating on this variable will be able to process it as an array. The second array is a standard way to define a numeric array, the syntax is pretty easy, namely array(element1, element2, element3...). Elements inside the array are separated by comma.

Since PHP 5.4, there is a shortcut syntax to define PHP arrays in similar way as javascript arrays. The syntax is simple, you enclose your array elements in square bracket []. You do, however, need to make sure that you are running at PHP 5.4 or above:

PHP:
$array1 = [];
$array2 = [0, 1, 2, 3, 4];


2. Creating an associative array:
An associative array, abbreviated as assoc, is what normally appear in most general purpose programming languages as hash map. The difference between an associative array and a numeric array is that it uses string as index instead of numbers. The string is given a unique name called 'key', which also serves as identifier for a specific array element. The key-value pair are easy to use in many cases.

To declare an associative array, use the symbol => to map a key to a value:

PHP:
$assoc = array("username" => "Hall of Famer", "email" => "halloffamer@mysidiaadoptables.com", "age" => 23);

// as of PHP 5.4, this syntax is valid:
$assoc = ["username" => "Hall of Famer", "email" => "halloffamer@mysidiaadoptables.com", "age" => 23];


3. Manipulating Array indexes and keys:
So far we have been able to create numeric and associative arrays, but they aint quite useful yet. We will need a way to reference to the array's element in a given index for numeric array, or key-value pair for associative array. To accomplish this, we simply use the square bracket to enclose the index number of key string. It is very easy to accomplish, the below example prints out the value for both $array and $assoc:

PHP:
$array = array(0, 1, 2, 3, 4);
$assoc =  array("username" => "Hall of Famer", "email" => "halloffamer@mysidiaadoptables.com", "age" => 23);
echo $array[0];  // prints 0
echo $array[3];  // prints 3
echo $assoc['username'];  // prints Hall of Famer
echo $assoc['age']; // prints 23

Note for numeric arrays, the index starts at 0, not 1. There is a reason why in my example the first element is 0, since I want you to keep that in mind that numeric arrays always start at index 0. Failing to account for this can result in severe programming flaws/errors.

Adding or overwriting elements/key-value pairs is also a straightforward task. After an array is created, you may just write the variable array followed by square bracket to create/edit array elements/key-value pairs. The below syntax illustrates how this can be done:

PHP:
$array = array(0, 1, 2, 3, 4);
$assoc =  array("username" => "Hall of Famer", "email" => "halloffamer@mysidiaadoptables.com", "age" => 23);
$array[5] = 5; // add a new element 5 at index 5
$array[0] = -1; // overwrite the element 0 at index 1 with a new value -1
$assoc['occupation'] = "Cruxis Seraph"; // append a new key-value pair occupation => Cruxis Seraph to associative array
$assoc['username'] = "Lord Yggdrasill"; // overwrite the key username with a new value Lord Yggdrasill

It is not complicated so far, is it? Now that you've learned the very basic operations for arrays, we will be moving on to the more complicated stuff about arrays next.


4. 'foreach' Loop on PHP Arrays:
Back in chapter 4 iterations/loops, I briefly introduced three basic loop structures that you can easily play with. There is another one that I chose not to bring up, since it involves arrays. It is perfect time to get into this 'foreach' loop structure since we are in the world of arrays now.

Since an array is a collection of elements, we will need to a way to iterate through its elements by following any possible order. We can use a while or for loop here, but we will need to keep track of the index or the current key, sometimes its easy to get lost. For associative arrays, it is an almost impossible task. With foreach loop, the work is greatly simplified as it is specifically designed for vector data type operations.

To create a foreach loop, the syntax is foreach($array as $element) for numeric arrays, and foreach($array as $key => $value) for associative arrays. The below code demonstrates how it actually works:

PHP:
$array = array(0, 1, 2, 3, 4);
$assoc =  array("username" => "Hall of Famer", "email" => "halloffamer@mysidiaadoptables.com", "age" => 23);

// loop through numeric array
foreach($array as $element){
    echo $element;
}
// print 01234 respectively

// loop through associative array
foreach($array as $key => $value){
    echo "{$key}: {$value}  ";
}
// pring username: Hall of Famer  email: halloffamer@mysidiaadoptables.com age: 23 respectively

Inside the loop body you can use the current element or key-value pair without worrying about what index/key the loop currently is at. A very useful example is to extract an array of database column information and loop through these elements. If you've followed us through Mys v1.2.x era, you might have seen such code being used extensively.


5. Some useful built-in Array functions:
The syntax of creating/manipulating arrays aint quite complex, but it is a different story if you need more powerful tools to play with arrays. There are a few commonly used Array functions that come bundled with PHP language itself, I will introduce a few of them to you here.

First of all, you can use the count() function to get the size of the array. It is the simplest function for array manipulation but it also is the most commonly used.
PHP:
$array = array(0, 1, 2, 3, 4);
echo count($array); //print 5 for the size of this array

Second, you can use the following three sorting functions to sort elements inside your array through alphanumeric order. The first function is useful for sorting numeric arrays, while the second function sorts an associative array based on its values, and the third function sorts an associative array based on its keys.

PHP:
$sorted_array = sort($array); // sort a numeric array
$sorted_array = asort($assoc); // sort a associative array based on value
$sorted_array = ksort($assoc); //sort an associative array based on key

If you want to sort the arrays in reverse order, simply add an r to the beginning of the the function so that it becomes: rsort, arsort and krsort. It cant get any easier.

Third, you can manipulate arrays by pushing a bunch of elements into array, merging two arrays together, or shifting the first element out from the array:

PHP:
$array = arraypush($array, 5, 6, 7); // add the three elements 5, 6 and 7 to $array = arraymerge($array1, $array2); // merge $array1 and array2 to become a new array
$first_element = arrayshift($array); // get the first element off from $array

At last but not least, you can check whether a value exists in a numeric or associative array. You can also retrieve an array of keys and values from an associative array to play with them. The below code demonstrates how those functions work:

PHP:
array_search($element, $array) // check if an element exists in a numeric/associative array
array_keys_exists($key, $assoc) // check if a key exists in an associative array
array_values($assoc) // returns an array of values from associative array
array_keys($assoc) // returns an array of keys from associative array
array_map("exp", $array) // apply the exponential function exp($element) on every element inside $array

So what do you think? Unfortunately this thread can only cover a small number of these array functions, you can read PHP's manual to find out more about PHP's built-in functions, many are really useful.


6. Multi-dimensional Arrays:

Another advanced feature about PHP arrays is that you can have an array whose elements are arrays, and thus making it a multi-dimensional array. The simplest example is a user collection array in which you have the first dimension of a collection being the username, and the second dimension being the user's detailed information such as ID, email and age. Below is an example of such multi-dimensional array:

PHP:
$multi_array = array("Hall of Famer" => array("ID" => 1, "email" => "halloffamer@mysidiaadoptables.com, "age"=> 23), 
                    array("Lord Yggdrasill" => array("ID" => 2, "email" => "lordyggdrasilll@gmail.com", "age" => 4014));

As you can see, this multidimensional array has 1-dimensional array as its element, thus making it a 2-dimensional array. foreach loops can be applied on multi-dimensional arrays too, although in most cases you end up with a nested loop that handles both the outer and inner layer of the 2-dimensional array. 3-dimensional arrays and n-dimensional arrays are rare to be found in the coder's world, and they can be difficult to maintain. The rule of thumb is to never go beyond 3-dimensional arrays, and in fact it is a good practice to keep it no greater than 2 dimensions.


This concludes the introduction to PHP arrays, hopefully you find it useful. As you can see from the examples provided above, PHP arrays are nothing complicated and should be easily understood if you've come this far. Array is one of the vector data types in PHP, the other is object which will be brought up for intermediate-skilled programmers tutorials that I will write after finishing up the entire beginners guides. The next chapter will discuss PHP strings, which should be straightforward too. Until then, have fun playing with the script and see how much you can do about it with the current level of knowledge you've learned from my tutorials.
 

Similar threads

Users who are viewing this thread

  • Forum Contains New Posts
  • Forum Contains No New Posts

Forum statistics

Threads
4,277
Messages
33,122
Members
1,602
Latest member
BerrieMilk
BETA

Latest Threads

Latest Posts

Top