Ch5 Array
Ch5 Array
Array
▸ An array is a special variable that can hold many values under a single name, and you can access the
values by referring to an index number or name.
2
Create Array
▸ You can create arrays by using the array() function:
▸ Multiple Lines: Line breaks are not important, so an array declaration can span multiple lines:
3
Create Array
▸ Trailing Comma: A comma after the last item ▸ Array Keys: When creating indexed arrays the
is allowed: keys are given automatically, starting at 0 and
increased by 1 for each item, so the array
above could also be created with keys:
4
Exercise
5
Array Types
▸ In PHP, there are three types of arrays:
▸ Array Items
• The most common are strings and numbers (int, float), but array items can also be objects,
functions or even arrays.
6
Indexed Arrays
▸ In indexed arrays each item has an index number.
▸ By default, the first item has index 0, the second item has item 1, etc.
7
Access Indexed Arrays
▸ To access an array item you can refer to the index number.
0 1 2
8
Change Value
▸ To change the value of an array item, use the index number:
0 1 2
9
Loop Through an Indexed Array
▸ To loop through and print all the values of an indexed array, you could use a foreach loop, like this:
10
Associative Arrays
▸ Associative arrays are arrays that use named keys that you assign to them.
11
Access Associative Arrays
▸ To access an array item you can refer to the key name.
12
Access Associative Arrays
▸ Double or Single Quotes: You can use both double and single quotes when accessing an array:
13
Change Value
▸ To change the value of an array item, use the key name:
14
Loop Through an Associative Array
▸ To loop through and print all the values of an associative array, you could use a foreach loop, like
this:
15
Exercise
16
Add Array Items
▸ To add items to an existing array, you can use the bracket [] syntax.
17
Add Array Items
▸ To add items to an associative array, or key/value array, use brackets [] for the key, and assign
value with the = operator.
18
Exercise
19
Delete Array Items
▸ Using the unset() Function
20
Delete Array Items
▸ The unset() function takes a unlimited number of arguments, and can therefore be used to delete
multiple array items:
21
Delete Array Items
▸ Remove Item From an Associative Array
▸ To remove items from an associative array, you can use the unset() function.
22