Arrays

Arrays

An array is a variable that can hold more than one value. Arrays in PHP are stored as value pairs that in other languages would be called a dictionary or a hashtable. Keys can be strings or integers.

Syntax

There are several methods of declaring an array in PHP. The array() function can be used, either with key-value pairs, or with values alone. Single brackets, [...] can also be used in place of the array() keyword. If any key value is omitted, the key will be found by incrementing the largest prior integer key. If a key is repeated, the new value will overwrite the prior key.

Loading...

Additionally, when defining an array, the following key casts will occur:

  • Strings containing valid int types, unless preceded by a + sign, will be cast to an int type key. As in the above example "5" is treated as 5.
  • float types will be cast to int types, truncating the fractional part. As in the above example 5.7 is treated as 5.
  • bool types are cast to int types. true is stored as 1 and false stored as 0.
  • null will be cast as the empty string, "".
  • Arrays and objects cannot be used as keys and will result in an error: Illegal offset type.
Interested in helping build Docs? Read the Contribution Guide or share your feedback.

Learn PHP on Codecademy