How to add elements to an array in PHP?

by elisha_langworth , in category: PHP General , a year ago

How to add elements to an array in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by gilbert , a year ago

@elisha_langworth 

In PHP, you can add elements to an array using several built-in functions:

  1. Using the array_push() function: The array_push() function adds one or more elements to the end of an array.
1
2
3
$fruits = array("apple", "banana");
array_push($fruits, "orange", "pear");
print_r($fruits);


Output:

1
2
3
4
5
6
7
Array
(
    [0] => apple
    [1] => banana
    [2] => orange
    [3] => pear
)


  1. Using the [] operator: You can add a new element to the end of an array using the [] operator.
1
2
3
$fruits = array("apple", "banana");
$fruits[] = "orange";
print_r($fruits);


Output:

1
2
3
4
5
6
Array
(
    [0] => apple
    [1] => banana
    [2] => orange
)


  1. Using the array_unshift() function: The array_unshift() function adds one or more elements to the beginning of an array.
1
2
3
$fruits = array("apple", "banana");
array_unshift($fruits, "orange", "pear");
print_r($fruits);


Output:

1
2
3
4
5
6
7
Array
(
    [0] => orange
    [1] => pear
    [2] => apple
    [3] => banana
)


  1. Using the array_merge() function: The array_merge() function merges one or more arrays into a single array.
1
2
3
4
$fruits1 = array("apple", "banana");
$fruits2 = array("orange", "pear");
$fruits = array_merge($fruits1, $fruits2);
print_r($fruits);


Output:

1
2
3
4
5
6
7
Array
(
    [0] => apple
    [1] => banana
    [2] => orange
    [3] => pear
)


These are just a few of the ways you can add elements to an array in PHP. There are many other array manipulation functions available in PHP that you can use depending on your needs.

by cali_green , 5 months ago

@elisha_langworth 

Additionally, you can use the array_push() function to add multiple elements at once or add elements at specific positions in the array using the array_splice() function.


To add multiple elements at once using array_push():

1
2
3
4
5
$fruits = array("apple", "banana");
$newFruits = array("orange", "pear");

array_push($fruits, ...$newFruits);
print_r($fruits);


Output:

1
2
3
4
5
6
7
Array
(
    [0] => apple
    [1] => banana
    [2] => orange
    [3] => pear
)


To add elements at specific positions using array_splice():

1
2
3
4
5
6
$fruits = array("apple", "banana", "mango", "grape");

// Insert "orange" at index 2
array_splice($fruits, 2, 0, "orange");

print_r($fruits);


Output:

1
2
3
4
5
6
7
8
Array
(
    [0] => apple
    [1] => banana
    [2] => orange
    [3] => mango
    [4] => grape
)


In this example, the third parameter of the array_splice() function is set to 0, which means no elements will be removed. The fourth parameter is the element to be added at the specified index.