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.

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.

There are many ways to output an array. Here we used the var_dump() function. Output should be like this :

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,

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.

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 :

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 :

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.

Sharing is Caring
Imtiaz Rayhan
 

WordPress Enthusiast, Novice PHP Developer. Music Addict, The Beatles Fan. Conncect with me on Facebook, Google+ and Twitter.

Click Here to Leave a Comment Below 0 comments

Leave a Reply: