Pages: 1 « previous     next »
Author Topic: Basic Intro to arrays in PHP  (Read 15602 times) Bookmark and Share
Jr. Member
Posts: 75

View Profile WWW
« on: Dec 28, 2011, 10:02:39 am »

Arrays are a special data type in PHP that is used to hold a list of data items. The ability to hold a list of data is valuable as it allows us to hold and pass sets of related data to different point in our application with ease.

Array Syntax
The simplest way to use arrays is to declare one using the array() function when declaring a variable.  There are a couple different ways to add data to an array, we can assign a value to the array with an empty index or by passing the values as parameters to the array() function.

When the array() function is used without any parameters an empty array is created.
Highlight Mode: (PHP)
  1. $ourList = array();

Passing values as parameters creates a non empty array. Passing a value to the array with an empty index also pushes a value to the end of the array.

Highlight Mode: (PHP)
  1. /* Fill an array by passing values as parameters */
  2. $ourList = array('Hello', 'World'); // pass values as parameters
  3. var_dump($ourList); // Visual Representation of the array.
  4. /* Filling an array by passing an empty index */
  5. $ourList2 = array(); // empty array
  6. $ourList2[] = 'Hello'; // pushes a value into the array
  7. $ourList2[] = 'World'; // pushes a value into the array
  8. var_dump($ourList2); // Visual Representation of the array.

Note: In the case that the array has not been explicitly created, simply using array syntax and assigning it a value will create an array with the key (if any) and values provided.

Array Indices
Arrays hold data as list and  list held by the array needs to be access in order to be useful. If you use a function like var_dump() or print_r() you can see a visual representation of the array like below:
Highlight Mode: (PHP)
  1. array(2) {
  2. [0]=>
  3. string(5) “Hello”
  4. [1]=>
  5. string(5) “World”
  6. }

Our array consists of two string values with a length of five characters. The important thing to notice is the value in the square brackets, this is the index that is used to refer to that value.

To access a given item in an array we simply use the name of the variable that holds the array and then use the index of the item in square brackets.

Highlight Mode: (PHP)
  1. # Fill an array by passing values as parameters
  2. $names = array('Leon', 'Ivan', 'John', 'Mohamed', 'Jose');
  3. echo $names[0], "<br>\n"; // Displays: Leon
  4. echo $names[1], "<br>\n"; // Displays: Ivan
  5. echo $names[2], "<br>\n"; // Displays: John
  6. echo $names[3], "<br>\n"; // Displays: Mohamed
  7. echo $names[4], "<br>\n"; // Displays: Jose
  8. # Visual representation of array.
  9. var_dump($names);

By default array indices begin at zero and count to one minus the number of elements. The array above has five elements and the indices range from zero to four.

Note: Indices can also be referred to as keys.

Specifying Indices (keys)
PHP automatically specifies the indices for arrays when none is specified. We can specify a different key starting point or do away with numerical numbering and use a string key names for our arrays indices.

To start numbering at a different value, we simply use the  “=>” operator when specifying values. Note that the parser will number any indices after that point in sequential order until a different index value is specified.

Highlight Mode: (PHP)
  1. $br = "<br>\n"; // Used for formatting
  2. /************************** EXAMPLE 1 ************************************/
  3. // Specify the count to start at 1 rather than 0
  4. $ourList = array(1 => 'Mercury', 'Venus');
  5. echo $ourList[1], $br; // Displays: Mercury
  6. echo $ourList[2], $br; // Displays: Venus
  7. /************************** EXAMPLE 2 ************************************/
  8. // Specify the a different index for certain values
  9. $ourList2 = array(1 => 'Mercury', 'Venus', 4 => 'Mars'); // 3 not defined!
  10. echo $ourList2[1], $br; // Displays: Mercury
  11. echo $ourList2[2], $br; // Displays: Venus
  12. echo $ourList2[3], $br; // Displays: Mars
  13. /************************** EXAMPLE 3 ************************************/
  14. // Specify a string key
  15. $ourList3 = array('home' => 'Earth', // key: home value: Earth
  16. 'largest' => 'Jupiter', // key: largest value: Jupiter
  17. 'center' => 'Sun', // key: center value: Sun
  18. 'Astroid Belt'); // key: 0 value: Astroid Belt
  19. echo $ourList3['home'], $br; // Displays: Earth
  20. echo $ourList3['largest'], $br; // Displays: Jupiter
  21. echo $ourList3['center'], $br; // Displays: Sun
  22. echo $ourList3[0], $br; // Displays: Astroid Belt

Note: PHP does not take white space into account when parsing code, for readability the example shows how we can set different keys and values on their own line. Arrays that contains string key names are referred to as associative arrays.

Arrays Inside Arrays
Arrays are nothing more than a list that holds other data types. Arrays can also be multi-dimensional, meaning that they can hold other arrays and those arrays can hold other arrays.
We can define arrays like the example below, or you can nest array() functions in one another.

Highlight Mode: (PHP)
  1. $family = array();
  2. // key 'adults' contains an array with keys and values
  3. $family['adults'] = array(
  4. 'mother' => 'Lea',
  5. 'father' => 'Lucas'
  6. );
  7. $family['children'] = array(
  8. 'son' => 'Leo',
  9. 'daughter' => 'Lisa'
  10. );
  11. echo $family['adults']['father'], "<br>\n"; // Displays: Lea
  12. echo $family['adults']['mother'], "<br>\n"; // Displays: Lucas
  13. echo $family['children']['son'], "<br>\n"; // Displays: Leo
  14. echo $family['children']['daughter'], "<br>\n"; // Displays: Lisa
  15. print_r($family); // Visual Representation of the array

Note: To access the data inside the inner array you specify a key of the array holding the inner array, then the key of the enclosed array.
Highlight Mode: (PHP)
  1. $variableName['outer array key']['inner array key'];
Note: This pattern continues if more arrays are enclosed.

Array Related Errors
While using arrays you may come across the following error.

Highlight Mode: (PHP)
  1. Notice: Undefined offset: key in file.php on line 20

Depending on the PHP setting on the server, this may or may not appear. In this example this is a PHP notice, which means the rest of our script will finish parsing and continue to be executed. If this was a fatal error our PHP script would stop executing all together.

This notice means that we have not defined this particular key for our array. To fix this you must specify the key the parser is trying to find at the line it specifies, or remove this reference all together, depending on what the script is supposed to be doing.

Arrays are a special data type in PHP that can hold a list of data including other arrays.  Arrays have sequential numerical keys (indices), but you have the ability to specify string key names or an alternate starting number. Arrays are commonly used to group related data in order to make it simple to pass the data to different parts of an application.
« Last Edit: Dec 28, 2011, 10:14:18 am by Max » Logged
Pages: 1
Jump to: