Home Logic Ubuntu (Linux) Blog

PHP: Index Arrays

  What is an array?

An array is a data type that holds a set of variables.



  Array Key

A key points to a particular value in an array. We use it to access the value it points to.



  Index Array

If you do not specify the names of your keys, they will automatically be indexed using numbers. The first value in the set with have an index of 0.

Say we have an array that stores types of caffinated beverages. Out of that set, we want to access "red bull". To access red bull, we can reference it's key.

Let's declare an index array called beverages. We declare the new array using the array function



Array Function


array(val1,val2,val3...)


Declaring an index array:


// declare beverage array
$beverages = array("Red Bull", "coffee", "tea", "pop");
        

In the example above, we did not specify keys. The elements contained in $beverages are indexed. That means the keys are {0,1,2,3}...

var redBull = $beverages[0];

"Red Bull" is the first element in $beverages, so it is indexed at 0. We can access it's value with: $beverages[0]



  Comprehension Check


************************
What is the key of each value in $beverages?

1)   Red Bull
2)   coffee
3)   tea
4)   pop
*************************

For more information on PHP arrays, check out the PHP offical documentation.