Adding Elements to an Array

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? Hopefully one of the 3 techniques shown below will help.

Defining an array with pre-existing values

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

$busy_period = array('May', 'June', 'July');
 
//display the contents of the array.
print_r($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.

$busy_period = array('May', 'June', 'July');
$busy_period[] =  'February';
 
//display the contents of the array.
print_r($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.

$busy_period = array('May', 'June', 'July');
array_push($busy_period, 'January', 'February');
 
//display the contents of the array.
print_r($busy_period);

Output

Array
(
    [0] => May
    [1] => June
    [2] => July
    [3] => January
    [4] => February
)

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.