PHP Arrays
Arrays allow us to assign multiple values into an array and store that into a variable.
First, we need to create a variable, and then we will store three items inside of an array
, and we do this inside of ()
.
$cars = array('BMW', 'Audi', 'Mercedes');
The different items inside the array have to be separated by a ,
.
If we try to echo out an array, it will give us an error because we can not echo out an array, but we can only echo out a specific index of our array.
Let's echo out the index of 1:
$cars = array('BMW', 'Audi', 'Mercedes');
echo $cars[1];
This will print out Audi
. If you're wondering why it's printing out the second item instead of the first one, that is because arrays start off at 0 instead of 1.
So let's print out the first item (BMW) in our array:
<?php
$cars = array('BMW', 'Audi', 'Mercedes');
echo $cars[0];
?>
It's crucial that you remember:
Arrays start off at
0
instead of1
!
If you really do need to print out your array, you can use a function called print_r
. This will print in a readable format your array.
$cars = array('BMW', 'Audi', 'Mercedes');
print_r($cars);