Single-Dimensional Arrays PHP

To refer to an element of an array, you use square brackets. Inside the brackets you put the index of the element, as in This construct may be treated exactly like a variable. You may assign a value or pass its value to a function. You do not have to declare anything about the array before you use it. Like variables, any element of an array will be created on the fly. If you refer to an array element that does not exist, it will evaluate to be zero or an empty string depending on the context.

Single-dimensional arrays are lists of values under a common name. But you might wonder, "Why bother?" You could just as easily create variables like "$Cities1, $Cities2, $Cities3" and not worry about square brackets. One reason is that it's easy to loop through all values of an array. If you know that all the elements of an array have been added using consecutive numbers, you can use a for loop to get each element. PHP makes it easy to create arrays that work this way; if you leave out an index when assigning an array element, PHP will start at zero and use consecutive integers thereafter. If you run the code in you will discover that the four cities have indexes of 0,1, 2, and 3.

Referencing Array Elements

Referencing Array Elements

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd Protection Status

PHP Topics