|
|
|
|
Arrays in PHP
Arrays in PHP allows us to store more values into one variable which makes access to the values much easier.
|
|
 |
|
|
|
|
|
 |
|
 |
|
 |
 |
1.
|
|
|
The most basic way to store values in PHP is to use variables with different names.
$car1 = "Saab"; $car2 = "Volvo"; $car3 = "BMW";
You can find out more about variables in
|
|
|
2.
|
|
|
In PHP and also in other programming languages there is also a more efficient way to store values in arrays.
To define an array we set name of a variable and add an index. Example with variable $cars:
$cars[0] = "Saab"; $cars[1] = "Volvo"; $cars[2] = "BMW"; $cars[3] = "Toyota";
echo $cars[0] . ", " . $cars[1];
In the example above we defined an array and used echo to print out the values.
|
|
|
3.
|
|
|
Short way for defining array is to use keyword array.
Instead of indexes we can also use names which can be seen in the example below.
$age = array("Peter" => 32, "John" => "57", "Sarah" => 23);
echo "Sarah is " . $age["Sarah"] . " years old.";
|
|
|
4.
|
|
|
Here we have another way to define the array which is a little longer, but the end result is exactly the same as in the previous step.
$age["Peter"] = 32; $age["John"] = 57; $age["Sarah"] = 23;
echo "John is " . $age["John"] . " years old.";
|
|
|
5.
|
|
|
We can also define multidimensional array which you can see in the example below.
$person["Peter"]["age"] = 32; $person["Peter"]["nickname"] = "Pete"; $person["Peter"]["hair"] = "Brown";
$person["John"]["age"] = 57; $person["John"]["nickname"] = "Johnny"; $person["John"]["hair"] = "Black";
echo "John is " . $person["John"]["age"] . " years old.";
|
|
|
6.
|
|
|
When we are working with arrays we can also use print_r function which will output all the indexes and values of the array.
$age["Peter"] = 32; $age["John"] = 57; $age["Sarah"] = 23;
print_r($age);
|
|
|
7.
|
|
|
One of the main advantages of using arrays is that you can easily access all the values by using foreach loop.
$age["Peter"] = 32; $age["John"] = 57; $age["Sarah"] = 23;
foreach($age as $key=>$value) { echo "Value of $key is $value. <br />"; }
By using foreach we go through all the keys in the array and print out the values.
If you want to know more about using loops in PHP please see
|
|
|
 |
 |
 |
|
 |
|
|