If you like SEOmastering Forum, you can support it by - BTC: bc1qppjcl3c2cyjazy6lepmrv3fh6ke9mxs7zpfky0 , TRC20 and more...

 

Specifying indices using array()

Started by chinmay.sahoo, 12-21-2015, 02:27:50

Previous topic - Next topic

chinmay.sahooTopic starter

The simple example of array() in the preceding section assigns indices to our elements, but those indices will be the integers, counting upward from zero—we're not getting a lot of choice in the matter. As it turns out, array() offers us a special syntax for specifying what the indices should be. Instead of element values separated by commas, you supply key-value pairs separated by commas, where the key and value are separated by the special symbol =>.

Consider the following statement:

Quote$fruit_basket = array(0 => 'apple', 1 => 'orange',
2 => 'banana', 3 => 'pear');

Evaluating it will have exactly the same effect as our earlier version—each string will be stored in the array in succession, with the indices 0, 1, 2, 3 in order. Instead, however, we can use exactly the same syntax to store these elements with different indices:

Quote$fruit_basket = array('red' => 'apple', 'orange' => 'orange',
'yellow' => 'banana', 'green' => 'pear');

This gives us the same four elements, added to our new array in the same order, but indexed by color names rather than numbers. To recover the name of the yellow fruit, for example, we just evaluate the expression:

Quote$fruit_basket['yellow'] // will be equal to 'banana'

Finally, as we said earlier, you can create an empty array by calling the array function with no arguments. For example:

Quote$my_empty_array = array();



If you like SEOmastering Forum, you can support it by - BTC: bc1qppjcl3c2cyjazy6lepmrv3fh6ke9mxs7zpfky0 , TRC20 and more...