Once an array exists in PHP, you can add extra elements to the array with the assignment operator (the equals sign), much like you can assign a value to a string or a number. When adding extra elements to the array, you can choose to either specify the key of the added element or leave this unspecified. In either case, you must refer to the array with the square brackets ([]). To add two items to the $list array, you would write:
If you do not specify the key, each element will be appended to the existing array, indexed with the next sequential number. Assuming this is the same array from the previous section, which was indexed at 1, 2, and 3, pears will now be located at 4 and tomatoes at 5.
If you do specify the index, the value will be assigned at that location. Any existing value already indexed at that point will be overwritten, like so:
As a result, the value of the element in the fourth position of the array will now be tomatoes, and no element of $list will be equal to oranges (this value will be overwritten by pears). With this in mind, unless you intend to overwrite existing data, you are best not to include a specific key when adding values to your arrays. However, if the array uses strings for indices, you will probably want to specify keys so you do not end up with an odd combination of string and number keys.
In this exercise you will test this process by rewriting coffee_types.php to add more elements to the array. To see the difference this will cause, you will be printing out the number of elements in the array before the new additions and after.
Just as you can find the length of a string— i.e., how many characters it contains—using strlen(), you can determine the number of elements in an array, using count():
Watch this video
Links
[1] https://www.studyanywhere.ca/advanced-courses/intro-php/chapter-7/using-arrays/exercise-3
[2] https://www.studyanywhere.ca/advanced-courses/intro-php/chapter-7/using-arrays/exercise-3#open_here
[3] https://www.studyanywhere.ca/advanced-courses/intro-php/chapter-7/using-arrays/exercise-3#open_here2
[4] https://www.studyanywhere.ca/sites/default/files/courses/202/videos/example-of-arrays-in-php.html
[5] https://www.studyanywhere.ca/advanced-courses/intro-php/chapter-1/getting-started-with-php/exercise-1#anchor
[6] https://www.studyanywhere.ca/advanced-courses/intro-php/chapter-7/using-arrays