Requirements

  • PHP running on your computer
  • Basic knowledge of PHP
  • Text Editor

Definition

array_push() is a PHP function that is used to add one or more elements onto the end of an array. The length of array increases by the number of variables pushed.

Your added elements will always have numeric keys, even if the array itself has string keys.

Syntax

array_push(_array, value1, value2, ..._)

Description

  • array is a required value. Specifies an array.
  • value1 is an opcional value. Specifies the value/element to add.
  • value2 is an opcional value. Specifies the value/element to add.
  • value1 is a required value in PHP versions before 7.3.

Usage

Open a php file and create an array of fruits.

<?php

$fruit = array('banana', 'orange');

print_r($fruit);

PHPCopy

Output

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

BashCopy

Let’s add some elements onto the end of fruit array.

<?php
$fruit = array('banana', 'orange');

// adding elements using array_push
array_push($fruit, 'mango', 'tangerine');

print_r($fruit);

PHPCopy

Output

Array
(
    [0] => banana
    [1] => orange
    [2] => mango
    [3] => tangerine

#snippets #php #snippets

PHP Add to Array | Push Value to Array PHP - array_push()
1.70 GEEK