Specifying indices using array()

Author Topic: Specifying indices using array()  (Read 502 times)

Offline chinmay.sahooTopic starter

  • Trade Count: (0)
  • Full Member
  • ***
  • Thank You 2
  • Posts: 139
  • Karma: 0
    • No Addiction
Specifying indices using array()
« on: 12-21-2015, 02:27:50 »
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:

$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:

$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:

$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:

$my_empty_array = array();


Related Topics

  Subject / Started by Replies Last post
1 Replies
Last post 05-30-2016, 21:09:23
by ngomaichi
0 Replies
Last post 08-11-2016, 07:22:02
by beingchinmay
0 Replies
Last post 09-23-2016, 06:19:03
by beingchinmay