Adding Elements to an array with a keyed index

Question:
In the previous example where I added the name of a month to an array, I want the key to reflect the actual month as well so that the array output looks like this:

Array
(
    [5] => May
    [6] => June
    [7] => July
)

Defining an array with pre-existing values and keys

You can specify the key and the value when you define the array.

$busy_period = array(5 => 'May', 6 => 'June', 7 => 'July');
 
//display the contents of the array.
print_r($busy_period);

Output

Array
(
    [5] => May
    [6] => June
    [7] => July
)

If you add another element onto the array without specifying the key, then php will automatically add the value onto the end of the array and increment the key accordingly. In this example, the next key php would insert would be 8.


Adding a single key and value to an array

The example below shows how to add a key indexed element to an array after its been defined.

$busy_period = array(5 => 'May', 6 => 'June', 7 => 'July');
$busy_period[2] = ‘February’;
 
//display the contents of the array.
print_r($busy_period);

Output

Array
(
    [5] => May
    [6] => June
    [7] => July
    [2] => February
)

When you add elements onto an array in the manner shown above, they are placed onto the end of the array, and this is reflected in the output. This may not be the desired effect because you may want the elements sorted based on their key value. This is covered in another article.

Comments

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.