5.4: Arrays

Section 5.4 Arrays Array variables are an essential tool in php. Array variables are useful for processing collections of data of the same type.

  • An array is a variable can hold one or more values.

  • If you have a list of items (a list of entertainers, for example), storing the entertainers in single variable could look like this:

Figure 5.4.1

  • We can store as many names in $entertainers as we like.

  • We would not want to include more than one type in a single array, e.g., it does not make sense to create an $entertainersArray and include a concert venue among the entertainer names. In fact this is precisely why we have an Object type, to store various kinds of data together.

  • Each member of the array is referenced by the array variable name, in this case it is $entertainers, along with subscript number.

  • The subscript numbering begins at zero. To access a particular value in the $entertainers array we would reference that value like this:

Figure 5.4.2

  • It is important understand that the array size is always 1 digit higher than the subscript number of the last item in the array. In our $entertainers array the size is 5 but the final subscript number is 4 since we start counting from zero. We will see why arraySize is important - and useful - shortly

  • Also note that in the example above the $singleEntertainer value is being overwritten by each of the three assignment statements from the $entertainers[n] variable.

  • We could print out our list of entertainers one-by-one using a hardcoded subscript shown below but that would be terrible inefficient and create a maintenance nightmare for anyone who needs to update the php code.

Figure 5.4.3

  • If we were reading the names into our php program from an external data source like a file and loading them into the array one-by-one then a developer would have to update the code every time a new entertainer is added to the file to allow space in the array.

  • To give you an appreciation for how powerful array values are we will need to move on to the next that introduces php loops.

Last updated