brenlei.com

PHP tutorials

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
)

Answer:

Defining an array with pre-existing values and keys

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

<?php
$busy_period = array(5 => 'May', 6 => 'June', 7 => 'July');

//display the contents of the array.
print_r($busy_period);

//Remove the array from memory
unset($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.

<?php
$busy_period = array(5 => 'May', 6 => 'June', 7 => 'July');
$busy_period[2] = ‘February’;

//display the contents of the array.
print_r($busy_period);

//Remove the array from memory
unset($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. more

Additional Notes

If this line:

$busy_period[2] = ‘February’;

Had been this instead (where we replace the 2 with a 5):

$busy_period[5] = ‘Feburary’;

Then the array element of May will be replaced with February.

PHP Reference Manual

array - Creates an array variable

print_r - Prints contents of an array

unset - Deletes a variable

Arrays

Adding Elements to an Array
Learn the different techniques of adding elements to an array, and see how they can be used in PHP scripts

Accessing the elements of an Array
This article shows examples of how-to access individual elements of an array.

Comments or questions relating to this article have been disabled. They will be back soon.