brenlei.com

PHP tutorials

Question:

I have a variable that only has a certain number of values, and I was thinking of putting the contents into an array. How do I do that?

Answer:

Defining an array with pre-existing values

The easiest way is to declare the array with the contents as shown in the example below.

<?php
$busy_period = array('May', 'June', 'July');
//display the contents of the array.
print_r($busy_period);

//Remove the array from memory
unset($busy_period);
?>
Output
Array
(
    [0] => May
    [1] => June
    [2] => July
)

Adding a single element to an array

There maybe circumstances where you need to ‘add’ values to an existing array. The example below shows how to add elements to an array.

<?php
$busy_period = array('May', 'June', 'July');
$busy_period[] =  'February';

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

//Remove the array from memory
unset($busy_period);
?>
Output
Array
(
    [0] => May
    [1] => June
    [2] => July
    [3] => February
)

Adding multiple elements to an array

You can add multiple elements to an array at the same time with the array_push function. This function adds the elements onto the end of the array list.

<?php
$busy_period = array('May', 'June', 'July');
array_push($busy_period, 'January', 'February');

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

//Remove the array from memory
unset($busy_period);
?>
Output
Array
(
    [0] => May
    [1] => June
    [2] => July
    [3] => January
    [4] => February
)

PHP Reference Manual

array - Creates an array variable

array_push - Pushes an element onto the end of an array

print_r - Prints contents of an array

unset - Deletes a variable

Arrays

Adding Elements to an array with a keyed index
Learn how to add elements to an array that have a key index, or where you need to specify one.

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

Sorting an Array
This article demonstrates techniques on how to sort the contents of an array, both with the keys and their values.

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