Mastering PHP’s array_push(): Syntax, Performance, and Real‑World Use Cases

This comprehensive guide explains PHP’s array_push function, covering its syntax, single‑ and multi‑element usage, performance comparisons with the [] syntax, common pitfalls, advanced patterns like stack implementation and pipelines, and practical examples such as dynamic SQL building and logging.

php Courses
php Courses
php Courses
Mastering PHP’s array_push(): Syntax, Performance, and Real‑World Use Cases

array_push() Overview

The built‑in PHP function array_push(array &$array, mixed ...$values): int appends one or more values to the end of an array passed by reference and returns the new number of elements. $array – target array (by reference). $values – one or more values to be added.

Return value – the array length after the operation.

Basic Usage

1. Push a single element

$fruits = ["apple", "banana"];
$newLength = array_push($fruits, "orange");
print_r($fruits); // Array ( [0] => apple [1] => banana [2] => orange )
echo "New length: $newLength"; // 3

2. Push multiple elements at once

$numbers = [1, 2, 3];
$newLength = array_push($numbers, 4, 5, 6);
print_r($numbers); // Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 )
echo "New length: $newLength"; // 6

3. Push into an associative array

$user = ["name" => "John", "age" => 30];
$newLength = array_push($user, "extra1", "extra2");
print_r($user); // Array ( [name] => John [age] => 30 [0] => extra1 [1] => extra2 )

Comparison with the [] Shorthand

Both array_push() and the [] operator can add elements, but they differ in performance and readability.

Performance test (10 000 iterations)

// array_push with multiple values
$start = microtime(true);
$arr1 = [];
for ($i = 0; $i < 10000; $i++) {
    array_push($arr1, $i, $i+1, $i+2);
}
$time1 = microtime(true) - $start;

// [] with multiple calls
$start = microtime(true);
$arr2 = [];
for ($i = 0; $i < 10000; $i++) {
    $arr2[] = $i;
    $arr2[] = $i+1;
    $arr2[] = $i+2;
}
$time2 = microtime(true) - $start;

// array_push with single value
$start = microtime(true);
$arr3 = [];
for ($i = 0; $i < 10000; $i++) {
    array_push($arr3, $i);
}
$time3 = microtime(true) - $start;

// [] with single value
$start = microtime(true);
$arr4 = [];
for ($i = 0; $i < 10000; $i++) {
    $arr4[] = $i;
}
$time4 = microtime(true) - $start;

echo "array_push (multiple): $time1
";
echo "[] (multiple): $time2
";
echo "array_push (single): $time3
";
echo "[] (single): $time4
";

For single‑element additions, [] is marginally faster.

When adding many elements at once, array_push() is usually more efficient because it performs a single function call.

Readability and Use‑Case Guidance

Single element – prefer [] for brevity.

Dynamic batch addition – use array_push($arr, ...$values) to push a variable‑length list.

Need the new length – array_push() returns the updated count.

Advanced Techniques

Spread operator for dynamic parameters

function addToCollection($collection, ...$items) {
    return array_push($collection, ...$items);
}

$data = ["a", "b"];
$newItems = ["c", "d", "e"];
$newLength = addToCollection($data, ...$newItems);
// or directly:
array_push($data, ...$newItems);

Simple stack implementation

class SimpleStack {
    private $items = [];
    public function push(...$elements) {
        return array_push($this->items, ...$elements);
    }
    public function pop() { return array_pop($this->items); }
    public function peek() { return end($this->items); }
    public function size() { return count($this->items); }
}

$stack = new SimpleStack();
$stack->push("doc1", "doc2");
echo $stack->pop(); // doc2

Pipeline for batch data processing

class DataProcessor {
    private $pipeline = [];
    public function addStage(callable $stage) {
        array_push($this->pipeline, $stage);
        return $this; // enable chaining
    }
    public function process($data) {
        foreach ($this->pipeline as $stage) {
            $data = $stage($data);
        }
        return $data;
    }
}

$processor = (new DataProcessor())
    ->addStage(fn($x) => $x * 2)
    ->addStage(fn($x) => $x + 10)
    ->addStage(fn($x) => $x / 2);

$result = $processor->process(5); // 10

Queue pattern using array_push and array_shift

$queue = [];
array_push($queue, "customer1", "customer2", "customer3");
while (!empty($queue)) {
    $current = array_shift($queue); // FIFO
    echo "Processing: $current
";
    if (rand(0,1) && count($queue) < 5) {
        array_push($queue, "new_customer_" . time());
    }
}

Common Pitfalls and Best Practices

Associative arrays – array_push() adds numeric keys, which may clash with existing keys. Use explicit key assignment (e.g., $arr["key"] = $value) for associative data.

Performance‑sensitive loops – avoid calling array_push() for single elements inside tight loops; the [] syntax is faster. Prefer batch pushes: array_push($arr, ...$batch).

Ignoring the return value – the function returns the new length; use it when the size matters (e.g., to trigger warnings when a queue grows too large).

Alternative Functions and Complementary Operations

array_unshift()

– prepend elements to the beginning of an array.

$queue = ["task2", "task3"];
array_unshift($queue, "task1"); // ["task1", "task2", "task3"]
array_merge()

and the + operator – concatenate arrays or preserve left‑hand keys.

$a1 = ["a", "b"];
$a2 = ["c", "d"];
$merged = array_merge($a1, $a2); // ["a","b","c","d"]

$assoc1 = ["a"=>1, "b"=>2];
$assoc2 = ["b"=>3, "c"=>4];
$combined = $assoc1 + $assoc2; // ["a"=>1, "b"=>2, "c"=>4]

PHP 7.4+ spread assignment – equivalent to array_push for sequential inserts.

$arr = [];
$arr[] = "first";
$arr[] = "second"; // same as array_push($arr, "first", "second")

Real‑World Application Cases

Dynamic SQL query builder

class QueryBuilder {
    private $conditions = [];
    private $params = [];
    public function where($field, $operator, $value) {
        $param = ':' . $field . count($this->params);
        $this->conditions[] = "$field $operator $param";
        array_push($this->params, $value);
        return $this;
    }
    public function build() {
        $sql = "SELECT * FROM users";
        if (!empty($this->conditions)) {
            $sql .= ' WHERE ' . implode(' AND ', $this->conditions);
        }
        return ['sql' => $sql, 'params' => $this->params];
    }
}

$qb = (new QueryBuilder())
    ->where('age', '>', 18)
    ->where('status', '=', 'active')
    ->build();
print_r($qb);

Log collector with size limit

class Logger {
    private $logs = [];
    private $maxSize = 1000;
    public function log($msg, $level = 'INFO') {
        $entry = ['timestamp'=>date('Y-m-d H:i:s'), 'level'=>$level, 'message'=>$msg];
        array_push($this->logs, $entry);
        if (count($this->logs) > $this->maxSize) {
            array_shift($this->logs); // drop oldest
        }
    }
    public function getRecent($limit = 10) {
        return array_slice($this->logs, -$limit);
    }
}

Processing multi‑select form fields

function processMultiSelect($field, $default = []) {
    $selected = $default;
    if (isset($_POST[$field])) {
        $submitted = (array)$_POST[$field];
        array_push($selected, ...$submitted);
        $selected = array_unique($selected);
    }
    return $selected;
}

$interests = processMultiSelect('interests', ['coding']);

Performance Optimisation Suggestions

Pre‑allocate large numeric arrays when the size is known:

$large = array_fill(0, 10000, null); // then assign by index

Prefer batch insertion over repeated single pushes:

$data = [];
$batch = generateLargeBatch(); // returns many items
array_push($data, ...$batch);

For very large indexed collections, consider SplFixedArray for lower memory overhead:

$fixed = new SplFixedArray(10000);

Summary

array_push()

is ideal for adding multiple elements at once and when the new length is required.

For single‑element additions, the [] syntax is more concise and slightly faster.

When used on associative arrays, array_push() creates numeric keys; explicit key assignment is safer.

Select the method that best fits readability, return‑value needs, and performance constraints.

best practicesarray_push
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.