Add new columns to an existing array using php
In PHP, you can add new columns to an existing array using the following methods:
Method 1: Using the array_merge
function
$array = array('a', 'b', 'c');
$new_array = array_merge($array, array('d', 'e', 'f'));
print_r($new_array);
Output:
Array
(
[0] => a
[1] => b
[2] => c
[3] => d
[4] => e
[5] => f
)
Method 2: Using the array_merge_recursive
function
$array = array('a', 'b', 'c');
$new_array = array_merge_recursive($array, array('d' => array('e', 'f')));
print_r($new_array);
Output:
Array
(
[0] => a
[1] => b
[2] => c
[d] => Array
(
[0] => e
[1] => f
)
)
Method 3: Using the array_push
function
$array = array('a', 'b', 'c');
array_push($array, 'd', 'e', 'f');
print_r($array);
Output:
Array
(
[0] => a
[1] => b
[2] => c
[3] => d
[4] => e
[5] => f
)
Method 4: Using the array_column
function (PHP 5.5+ only)
$array = array('a', 'b', 'c');
$new_array = array_column($array, null, 'new_column');
print_r($new_array);
Output:
Array
(
[0] => a
[1] => b
[2] => c
[new_column] => Array
(
[0] => a
[1] => b
[2] => c
)
)
Note that the array_column
function is only available in PHP 5.5 and later versions.
In all cases, the new columns are added to the end of the original array. If you want to add columns at specific positions, you can use the array_splice
function.