Arrays in PHP
Arrays are variables with a super power. While an ordinary variable can contain a single value, an array can contain multiple values at a time.
Previously, when we discussed data types in PHP, we saw that booleans, integers, floats – these can represent only one value at a time. But arrays can contain more than one values at a time and you can access the values by using a index number or keys. Let’s check an example.
<?php $numbers = array( 1, 2, 3, 4, 5 ); ?>
Arrays are created using the array() function. Here we created an array with 5 values and stored the array on a variable.
There are two types of arrays in PHP.
Indexed arrays and Associative arrays.
Indexed arrays are arrays with numeric index. The example shown above is an indexed array. Here is an important fact about indexed arrays. The index of an array starts from 0, not 1.
For example, let’s try to output the array we’ve created.
<?php $numbers = array( 1, 2, 3, 4, 5); var_dump($numbers); ?>
There are many ways to output an array. Here we used the var_dump() function. Output should be like this :
array (size=5) 0 => int 1 1 => int 2 2 => int 3 3 => int 4 4 => int 5
We can see the array with additional details. size=5 tells us that we have five values in this array. ‘int’ stands for integer. That means respected value is an integer.
Now notice how 1 is shown under 0 key/index. The index of the array started from 0. This is something you have to get used to.
There are other ways to output values from an indexed array. You can fetch values using their index numbers. For example,
<?php $numbers = array( 1, 2, 3, 4, 5); echo $numbers['0']; ?>
This will show the first value of the array. If we use 1 instead of 0, output will show 2.
Associative arrays are arrays where a key is associated with values. When we created indexed arrays with didn’t associate any keys with the values. Now we will. Let’s check an example.
<?php $myinfo = array ( "Name" => "Imtiaz Rayhan", "Age" => "20", "Country" => "Bangladesh" ); var_dump($myinfo); ?>
This is an associative array. Check how I associated keys with values. Again I used var_dump() function to output my array. Output should be like this :
array (size=3) 'Name' => string 'Imtiaz Rayhan' (length=13) 'Age' => string '20' (length=2) 'Country' => string 'Bangladesh' (length=10)
You can also output values using the Keys. Now let’s check how we can output the values using keys. For instance, if we want to show the name from the array, this is how we should do :
<?php $myinfo = array ( "Name" => "Imtiaz Rayhan", "Age" => "20", "Country" => "Bangladesh" ); echo $myinfo['Name']; ?>
Now if you run this on your browser, you will see the Values associated to the key Name. For me, I will see Imtiaz Rayhan. If you use your own name, you will see that.
These are the basics of Arrays in PHP. Let me know if you have any questions.