How to Push Value to Array in PHP
Table of Contents
Arrays are so useful because they allow us to hold multiple different values inside a single variable.
One of the most common operations of arrays is pushing a value to the end of the array.
In this post, we'll learn how to define an array in PHP and how to push a new element to the end of it.
Pushing a Value to the End of an Array
To push a value to an array, let's first start with our array:
PHP$array = [1, 2, 3];
From here, we can use the built-in array_push()
function to push a new value to the end of the array. This function is very simple to use, simply pass in the array and the value you want to push to the end of the array.
Let's say we wanted to add the number 4
to this array:
PHP$array = [1, 2, 3];
array_push($array, 4);
print_r($array);
BASHArray
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
Keep in mind that you can also use this function to add multiple values to the end of an array.
PHP$array = [1, 2, 3];
array_push($array, 4, 5, 6);
print_r($array);
BASHArray
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
)
Conclusion
In this post, we looked at defining an array in PHP and then pushing a value to the end of it.
We also looked at how to add multiple values to the end of an array using the same array_push()
function.
Thanks for reading!
- Getting Started with Svelte
- Create an RSS Reader in Node
- How to Serve Static Files with Nginx and Docker
- Best Visual Studio Code Extensions for 2022
- How to deploy a PHP app using Docker
- How to deploy a MySQL Server using Docker
- Using Puppeteer and Jest for End-to-End Testing
- How to Scrape the Web using Node.js and Puppeteer
- Learn how to build a Slack Bot using Node.js
- Building a Real-Time Note-Taking App with Vue and Firebase
- Getting Started with React
- Setting Up a Local Web Server using Node.js