Demystifying PHP’s Array Key/Index

According to php.net manual:

An array in PHP is actually an ordered map. A map is a type that associates values to keys.

A key may be either an integer or a string. If a key is the standard representation of an integer, it will be interpreted as such (i.e. “8” will be interpreted as 8, while “08” will be interpreted as “08”). Floats in key are truncated to integer. The indexed and associative array types are the same type in PHP, which can both contain integer and string indices.

Well, that’s just a bit of definition about Array and it’s key/index.
Let’s play with some practical examples.
Suppose say you are making a dropdown field for Opacities(0, 0.1, 0.2, … 0.9, 1) for your System > Configuration field (Magento) and using your source model as:

<?php
class MagePsycho_Custommodule_Model_System_Config_Source_Opacity
{
    public function toOptionArray()
    {
        $range = range(0, 1, 0.1);
        $array = array();
        foreach($range as $val){
            $array[$val] = $val;
        }
        return $array;
    }
}

When you try to load the page in System > Configuration for your module you will see that only there is only one value in dropdown i.e.

<option value="0">1</option>

You must be wondering where are the other values (0 – 0.9)?
Now the role of the key/index comes into play.

As per the above definition: An array key/index can only be an integer or a string type. But here index is a float type and PHP will convert it to an integer type and any float value: 0.1 – 0.9 will be converted to an integer: 0.

But if you modify the above code as:

<?php
class MagePsycho_Custommodule_Model_System_Config_Source_Opacity
{
    public function toOptionArray()
    {
        $range = range(0, 1, 0.1);
        $array = array();
        foreach($range as $val){
            $array["$val"] = $val; //note the double quotes around the key
        }
        return $array;
    }
}

You must have noted the double quotes around the key and using the double quotes will populate all the values from 0 – 1.
This is because PHP tries to interpolate the variable inside the double quotes and return a string. And the key looks like: For example:

$array['0.9']

which is a string key, not a float one.

Hope this helps you to get some understanding of proper usage of indexing in an Array.
Thanks for Reading!