Code Logo

Add Elements with array_push()

Published at25 Jul 2026
PHP Data Structures Easy 0 views
Like0

Write a PHP function that takes an array and a value, adds the value to the array using array_push(), and returns the new length of the array using count().

array_push() is a PHP function that adds one or more elements to the end of an array. It returns the new number of elements in the array. Unlike $arr[] = $val which can only add one element, array_push() can add multiple at once: array_push($arr, $v1, $v2, $v3).

count() returns the number of elements in an array or Countable object. It is one of the most commonly used PHP functions for array operations. For arrays, count() has O(1) complexity as the length is stored internally.

Both array_push() and count() are fundamental PHP array operations. Understanding them is essential for working with dynamic arrays in PHP.

Example Input & Output

Example 1
Input
[1,2,3],4
Output
4
Explanation

Push 4 to [1,2,3] gives length 4

Example 2
Input
([1,2,3,4],5)
Output
5
Explanation

Push 5 to [1,2,3,4] gives length 5

Example 3
Input
([10],20)
Output
2
Explanation

Push 20 to [10] gives length 2

Example 4
Input
[],5
Output
1
Explanation

Push to empty array gives length 1

Example 5
Input
([0],0)
Output
2
Explanation

Push 0 to [0] gives length 2

Algorithm Flow

Recommendation Algorithm Flow for Add Elements with array_push()
Recommendation Algorithm Flow for Add Elements with array_push()

Solution Approach

function solution($arr, $val) {
    array_push($arr, $val);
    return count($arr);
}

Best Answers

php - Approach 1
<?php
function solution($arr, $val) {
    array_push($arr, $val);
    return count($arr);
}