How to add elements to an array in PHP?

by elisha_langworth , in category: PHP General , 6 months ago

How to add elements to an array in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by gilbert , 6 months 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.