Add Elements with array_push()
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
Push 4 to [1,2,3] gives length 4
Push 5 to [1,2,3,4] gives length 5
Push 20 to [10] gives length 2
Push to empty array gives length 1
Push 0 to [0] gives length 2
Algorithm Flow

Solution Approach
Best Answers
<?php
function solution($arr, $val) {
array_push($arr, $val);
return count($arr);
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
