Mysidia Adoptables Support Forum  

Home Community Mys-Script Creative Off-Topic
Go Back   Mysidia Adoptables Support Forum > Mysidia Adoptables > Tutorials and Tips

Notices

Reply
 
Thread Tools Display Modes
  #1  
Old 03-16-2013, 07:14 PM
Hall of Famer's Avatar
Hall of Famer Hall of Famer is offline
Administrator, Lead Coder
 
Join Date: Dec 2008
Location: South Brunswick
Posts: 4,448
Gender: Male
Credits: 334,155
Hall of Famer is on a distinguished road
Default Hall of Famer's PHP Tutorials: Chapter 6 - PHP Arrays

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 Code:
$array1 = array();
$array2 = array(01234); 
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 Code:
$array1 = [];
$array2 = [01234]; 

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 Code:
$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 Code:
$array = array(01234);
$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 Code:
$array = array(01234);
$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 Code:
$array = array(01234);
$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 Code:
$array = array(01234);
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 Code:
$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 Code:
$array arraypush($array567); // 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 Code:
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 Code:
$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.
__________________


Mysidia Adoptables, a free and ever-improving script for aspiring adoptables/pets site.
Reply With Quote
Reply


Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Hall of Famer's PHP Tutorials: Chapter 5 - PHP Function Basics Hall of Famer Tutorials and Tips 0 11-23-2012 01:05 AM
Hall of Famer's PHP Tutorials: Chapter 1 - PHP syntax Hall of Famer Tutorials and Tips 10 02-02-2012 10:31 AM
Hall of Famer's PHP Tutorials: Chapter 4 - PHP Iteration Hall of Famer Tutorials and Tips 2 02-26-2011 09:48 AM
Hall of Famer's PHP Tutorials: Chapter 3 - PHP Conditional Statements Hall of Famer Tutorials and Tips 0 02-23-2011 05:59 PM
Hall of Famer's PHP Tutorials: Chapter 2 - PHP Operators Hall of Famer Tutorials and Tips 0 02-22-2011 07:26 PM


All times are GMT -5. The time now is 12:40 PM.

Currently Active Users: 9821 (0 members and 9821 guests)
Threads: 4,080, Posts: 32,024, Members: 2,016
Welcome to our newest members, jolob.
BETA





What's New?

What's Hot?

What's Popular?


Powered by vBulletin® Version 3.8.11
Copyright ©2000 - 2024, vBulletin Solutions Inc.
vBCommerce I v2.0.0 Gold ©2010, PixelFX Studios
vBCredits I v2.0.0 Gold ©2010, PixelFX Studios
Emoticons by darkmoon3636