How to use array_push in php?

Summary

In this post, we will learn PHP array_push()‘s inner workings, syntax, and usage cases to illustrate how valuable they are in a variety of contexts.

Introduction

The array_push() function is useful to add values to an existing array. It’s commonly used to append new elements to the end of an existing array.

Syntax

The syntax of array_push() is simple:

array_push($array, $val1, $val2, …)

Parameters

1. $array :  The targeted or source array in which value(s) needs to be added.Type should be Array.

2. list of elements : Elements which we have to insert.In above syntax  $val1, $val2, … are the elements.Type should be any one from Integer, String, Float, Array.

Array_push accepts two minimum value(s) that are the targeted array and the value(s) to be appended.The new number of entries in the array following the addition(s) is shown in the return value.

Examples

Example 1: Basic Usage

<?php

$fruitsArray = ["apple", "banana"];

array_push($fruitsArray, "orange");

?>

Result

Array
(
    [0] => apple
    [1] => banana
    [2] => orange
)

Example 2: Appending Multiple Elements

<?php

$numberArray = [1, 2];

array_push($numberArray, 3, 4, 5);

?>

Result

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)

Example 3: Dynamic User Input

<?php

$userList = ["David"];

$newUser = "John";

array_push($userList, $newUser);

?>

Result

Array
(
    [0] => David
    [1] => John
)

Example 4: Merging Arrays

<?php

$firstArray = [1, 2];

$secondArray = [3, 4];

array_push($firstArray, ...$secondArray);

?>

Result

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)

Frequently Asked Questions

Q1.What is array_push in PHP?

Ans: array_push() is a built-in function in the PHP programming language that is used to add one or more elements to the end of an array. It’s commonly used to append new elements to the end of an existing array. This function takes the array you want to modify as its first argument, followed by the value or values you want to add to the end of the array.

Q2. How to use push array in PHP?

  • Using square brackets [] notation : We can simply use the empty square brackets [] to add an element to the end of an array
  • Using array_push() function: The array_push() function can be used to add one or more elements to the end of an array.

Q3. Is array_push in PHP or Javascript?

Ans : array_push() is a function in PHP that is used to add one or more elements to the end of an array. It’s not available in JavaScript.

Q4. How to get array output in PHP?

Ans : The print_r() or var_dump()  function are used to display the entire array.

Conclusion:

array_push() is a crucial function for managing arrays with dynamic and changing content in the world of PHP development. Using the array_push() will surely increase your programming productivity and maintainability, whether you’re developing a tiny application or a complex system.

%d bloggers like this: