PHP: How to insert value into array

[notice]As this is one of the most hit articles on the site, I’ve decided to update and build on it, it is now targeted at PHP 5.0+.[/notice]
There are two ‘main’ forms of arrays within PHP, these are numerical (or zero based) and associative arrays.

Creating a new array

The code below demonstrates creating a new array:

$arr = new array();

This is the same for numerical and associative arrays.

Numerical Arrays

You can think of numerical arrays as collections of variables (strings, integers, etc) that are index by a number.

Adding to a numerical array

We can add to a numerical array in three ways:

$arr = new array("Value 1","Value 2");    //Create the array & add the values
var_dump($arr);    //Print the contents of the array to screen

You can also push values to an array:

$arr = new array();    //Create the array
array_push($arr, 'Value 1');    //'Push' the value into the next available index
array_push($arr, 'Value 2');    //'Push' the value into the next available index
var_dump($arr);    //Print the contents of the array to screen

You can also add to array by directly setting the index:

$arr = new array();    //Create the array
$arr[0] = 'Value 1';    //'Set' index 0 to the value
$arr[1] = 'Value 2';    //'Set' index 1 to the value
var_dump($arr);    //Print the contents of the array to screen

Both methods will produce the same outcome, the downfall of the second method is that you must know the index you would like to set. The contents of the array if dumped would be:

array(2) {
 [0]=>
 string(7) 'Value 1'
 [1]=>
 string(7) 'Value 2'
 }

Associative Arrays

Associative arrays are index by a key, the key can be any PHP variable (string, integer, etc).

Adding to an associative array

There are two methods of adding to an associative array:

$arr = new array("key1"=>"Value 1", "key2"=>"Value 2");    //Create the array & add the values
var_dump($arr);    //Print the contents of the array to screen

You can set the index directly:

$arr = new array();    //Create the array
$arr['key1'] = "Value 1";   //Set the index and set the value
$arr['key2'] = "Value 2";   //Set the index and set the value
var_dump($arr);    //Print the contents of the array to screen

Both methods will produce the same outcome, you must know the index you would like to set. The contents of the array if dumped would be:

array(2) {
 ['key1']=>
 string(7) 'Value 1'
 ['key2']=>
 string(7) 'Value 2'
 }


Leave a Reply

Your email address will not be published. Required fields are marked *