Menu
Coddy logo textTech

Adding with 'array_push'

Part of the Logic & Flow section of Coddy's PHP journey — lesson 10 of 68.

The array_push() function is a convenient way to add one or more elements to the end of an indexed array. This function modifies the original array directly, making it longer by appending new values.

Here's the basic syntax:

<?php
$fruits = ["apple", "banana"];
array_push($fruits, "orange");
print_r($fruits);  // Outputs: Array ( [0] => apple [1] => banana [2] => orange )
?>

You can also add multiple elements at once by passing additional arguments:

<?php
$colors = ["red", "blue"];
array_push($colors, "green", "yellow", "purple");
print_r($colors);  // Outputs: Array ( [0] => red [1] => blue [2] => green [3] => yellow [4] => purple )
?>

The function returns the new length of the array after adding the elements. This makes array_push() particularly useful when you need to dynamically build lists, such as shopping carts, to-do lists, or any collection where you're continuously adding items to the end.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

challenge icon

Challenge

Easy

You will receive two inputs: an initial array of items in JSON format and a new item to add. Read both inputs, convert the JSON string to an array, use array_push() to add the new item to the array, and print the final array using print_r().

Input format: Two lines - first line contains a JSON array (example: ["apple","banana"]), second line contains the new item to add

Expected output: The array after adding the new item, displayed using print_r()

Cheat sheet

The array_push() function adds one or more elements to the end of an indexed array and modifies the original array directly.

Basic syntax:

array_push($array, $element1, $element2, ...);

Adding a single element:

$fruits = ["apple", "banana"];
array_push($fruits, "orange");
// Result: ["apple", "banana", "orange"]

Adding multiple elements:

$colors = ["red", "blue"];
array_push($colors, "green", "yellow", "purple");
// Result: ["red", "blue", "green", "yellow", "purple"]

The function returns the new length of the array after adding the elements.

Try it yourself

<?php
// Read the JSON array input
$jsonInput = trim(fgets(STDIN));
$items = (array)json_decode($jsonInput, true);

// Read the new item to add
$newItem = trim(fgets(STDIN));

// TODO: Write your code below to add the new item to the array using array_push()


// Output the final array
print_r($items);
?>
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow