The PHP Array
Currently, a more modern approach
is to create an array using square
brackets [ ], like this:
<?php
$arr = ['a', 'b', 'c'];
?>
You can access any element by its number
(zero-based numbering). Let's output, for example, the element
'a':
<?php
$arr = ['a', 'b', 'c'];
echo $arr[0]; // outputs 'a'
?>
And now the element 'b':
<?php
$arr = ['a', 'b', 'c'];
echo $arr[1]; // outputs 'b'
?>
You can create arrays with custom keys. Such arrays are called associative. Let's create such an array:
<?php
$arr = ['key1' => 1, 'key2' => 2, 'key3' => 3];
?>
Let's output, for example, the element with the key
'key1':
<?php
$arr = ['key1' => 1, 'key2' => 2, 'key3' => 3];
echo $arr['key1']; // outputs 1
?>
And now with the key 'key2':
<?php
$arr = ['key1' => 1, 'key2' => 2, 'key3' => 3];
echo $arr['key2']; // outputs 2
?>
See Also
-
lesson
arrays in PHP