What is the difference between array_push() and array_unshift()?

Introduction

In PHP, both array_push() and array_unshift() are used to manipulate arrays, but they serve different purposes and operate differently. Understanding their differences is essential for effective array management in your PHP code.

array_push()

Overview

The array_push() function adds one or more elements to the end of an array. It is useful when you need to append data to the end of an existing array.

Usage

Here is an example of using array_push():

$array = array(1, 2, 3);
array_push($array, 4, 5);
// $array now contains 1, 2, 3, 4, 5

Performance

array_push() is generally efficient for adding elements to the end of an array, as it does not require reindexing the array"s elements.

array_unshift()

Overview

The array_unshift() function adds one or more elements to the beginning of an array. It is useful when you need to prepend data to the start of an array.

Usage

Here is an example of using array_unshift():

$array = array(1, 2, 3);
array_unshift($array, 0, -1);
// $array now contains 0, -1, 1, 2, 3

Performance

array_unshift() can be less efficient compared to array_push() because it requires reindexing the array"s elements to accommodate new elements at the beginning.

Key Differences

  • Position of Addition: array_push() adds elements to the end, while array_unshift() adds elements to the beginning.
  • Performance Impact: array_push() is generally faster for appending elements, whereas array_unshift() may impact performance due to reindexing.
  • Use Cases: Use array_push() when you need to append items to an array, and array_unshift() when you need to prepend items.

Conclusion

Both array_push() and array_unshift() are valuable functions in PHP for manipulating arrays. The choice between them depends on whether you need to add elements to the end or the beginning of an array, as well as considerations of performance and use case.

18 Aug 2024   |    14

article by ~ raman gulati

Top related questions

How do `echo` and `print` differ in PHP?

18 Aug 2024

   |    28

How Do `isset()` and `empty()` Differ in PHP?

18 Aug 2024

   |    19

How do foreach and for loops differ in PHP?

18 Aug 2024

   |    13

Difference Between Procedural and OOPs in PHP

18 Aug 2024

   |    14

Related queries

Latest questions