This is an introduction to PHP arrays, so if you are new to the language or you just need a refresher you can get up to speed pretty fast.
This is how we initialize an empty array and add some elements to it:
|
1 2 |
$chars = array(); array_push($chars,'a','b','c'); |
Then we can see it’s contents using the print_r() function. You may want to put this between <pre> tags for better formatting.
|
1 |
print_r($chars); |
Output:
|
1 2 3 4 5 6 |
Array ( [0] => a [1] => b [2] => c ) |
Another useful operation with arrays is knowing how many elements it contains. For that we can use the count() function.
|
1 2 3 |
$size = count($chars); echo $size; echo ""; |
One thing worth noting about php arrays is that they behave like hash maps. Because arrays are just key/value pairs, we can add a new pair like this:
|
1 |
$chars['name'] = 'John'; |
Now let’s see how we can iterate through arrays, using the foreach() function.
|
1 2 3 4 |
foreach ($chars as $char) { echo $char; echo ""; } |
If we also want the keys and not just the values, we can do this:
|
1 2 3 4 |
foreach ($chars as $key =>; $value ) { echo "Key: " . $key . " Value: ". $value; echo ""; } |
Output:
|
1 2 3 4 |
Key: 0 Value: a Key: 1 Value: b Key: 2 Value: c Key: name Value: John |
You can download the example code here:
https://gist.github.com/3801039
Array function reference: http://php.net/manual/en/ref.array.php