From what I have learned about arrays
and using the foreach
loop, I find it easy to look at it this way.
<?php
print('<h1>First array</h1>');
$array1 = array(1, 2, 3, 4, 5); // This array doesn't have any keys
foreach($array1 as $key1 => $value1) {
print('Key: ' . $key1);
print('<br />');
print('Value: ' . $value1);
print('<br /><br />');
}
print('<br /><br />');
print('<h1>Second array</h1>');
$array2 = array(1 => 'First key', 2 => 'Second key', 3 => 'Third key', 4 => 'Fourth key', 5 => 'Fifth key'); // This array DOES have keys
foreach($array2 as $key2 => $value2) {
print('Key: ' . $key2);
print('<br />');
print('Value: ' . $value2);
print('<br /><br />');
}
Where you don’t declare a key in the array, PHP
will increment a key for you starting from 0. The key itself can actually be anything you want. It can be a string or an integer. Take this third array for example.
print('<h1>Third array</h1>');
$array3 = array('first_key' => 'First key description', 'second_key' => 'Second key description', 'third_key' => 'Third key description', 'fourth_key' => 'Fourth key description', 'fifth_key' => 'Fifth key description'); // This array has custom keys.
foreach($array3 as $key3 => $value3) {
print('Key: ' . $key3);
print('<br />');
print('Value: ' . $value3);
print('<br /><br />');
}
The keys from this array will return
first_key, second_key, third_key, fourth_key, fifth_key
And the values from this array will return
First key description, Second key description, Third key description, Fourth key description, Fifth key description
Without actually increment the key itself. So if you specify the key in your array
, PHP
will use those keys. But if you don’t specify the keys in your arrays
, PHP
will increment the key starting from 0 for you. If you set the key manually starting from 1, it’ll most likely use 1 and so on unless you are inconsistent and use a string in between the numeric keys.
For slow learners and beginners, the first argument of the foreach
loop ALWAYS HAS to be an array
. The second argument is actually optional unless you want to do something with the keys. And the third argument is always the returned value of the array with or without the keys.