This post will help you understand what an array is and how it is used.
In this three part series I will will go over:
- What is an array
- Creating arrays
- Testing for an array
- Adding and removing array elements
- Locating array elements
- Traversing Arrays
- Determining array Size and element uniqueness
- Sorting arrays
- Merging, slicing, splicing and dissecting arrays
What is an array?
A traditional array is defined as a group of items that share certain characteristics such as similarity and type.
- Examples of Similarity might be something like “car models”, “baseball teams” or “types of fruit”.
- Examples of types might be something like “string” or “integers”
- *NOTE* The items DON’T have to groups of similar items.
There are two main parts of an array. The array is made up of a key and a value. While “Value” is pretty obvious the key is something a lot of beginning programmer have an issue with. Keys can be one of two types. Numerical or Associative. Associative keys ten to bear some relation to the value other then its array position.
An example of a numeric array being defined:
<?php
$provinces[0] = "BC";
$provinces[1] = "Alberta";
$provinces[2] = "Saskatchewan";
$provinces[3] = "Ontario";
?>
The key’s in this example are “0”, “1”, “2”, “3”.
An example of an Associative array being defined:
<?php
$provinces[BC] = "Vancouver";
$provinces[AB] = "Calgary";
$provinces[SK] = "Regina";
$provinces[MB] = "Winnipeg";
$provinces[ON] = "Toronto";
?>
Notice now how I used strings instead of numbers for the key identifier? The key’s also make more sense then using 0,1,2 etc.
Outputting Arrays
The easiest way of quickly outputting an array in php is by using the print_r() function. The output isn’t very nice but it allows you to see what’s all in the array. To use the print_r() function you would type:
print_r($provinces);
Here’s an example of the output of associative array above using print_r() function.
Array ( [BC] => Vancouver [AB] => Calgary [SK] => Regina [MB] => Winnipeg [ON] => Toronto )
sd
[…] Link: PHP – All about arrays (Part 1 of 3) | Jared Heinrichs […]