Adding with 'array_unshift'
Part of the Logic & Flow section of Coddy's PHP journey — lesson 12 of 68.
While array_push() adds elements to the end of an array, the array_unshift() function does the opposite—it adds one or more elements to the beginning of an array. This function modifies the original array directly and returns the new length of the array.
Here's the basic syntax:
<?php
$tasks = ["buy groceries", "do laundry"];
array_unshift($tasks, "urgent meeting");
print_r($tasks); // Outputs: Array ( [0] => urgent meeting [1] => buy groceries [2] => do laundry )
?>Notice how the new element becomes index 0, and all existing elements shift to higher indices. This re-indexing happens automatically—array_unshift() updates all the numeric keys to maintain the proper sequence.
You can also add multiple elements at once:
<?php
$priorities = ["medium task"];
array_unshift($priorities, "high priority", "critical task");
print_r($priorities); // Outputs: Array ( [0] => high priority [1] => critical task [2] => medium task )
?>This function is particularly useful when you need to prioritize items in a list, such as adding urgent tasks to the top of a to-do list or inserting high-priority items at the front of a queue.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyYou will receive two inputs: an initial array of notifications in JSON format and a new urgent notification to add. Read both inputs, convert the JSON string to an array, use array_unshift() to add the urgent notification to the beginning of the array, and print the final array using print_r().
Input format: Two lines - first line contains a JSON array (example: ["meeting reminder","email received"]), second line contains the urgent notification to add
Expected output: The array after adding the urgent notification at the beginning, displayed using print_r()
Cheat sheet
The array_unshift() function adds elements to the beginning of an array, modifying the original array and returning its new length:
<?php
$tasks = ["buy groceries", "do laundry"];
array_unshift($tasks, "urgent meeting");
print_r($tasks); // Outputs: Array ( [0] => urgent meeting [1] => buy groceries [2] => do laundry )
?>New elements become index 0, and existing elements shift to higher indices automatically.
You can add multiple elements at once:
<?php
$priorities = ["medium task"];
array_unshift($priorities, "high priority", "critical task");
print_r($priorities); // Outputs: Array ( [0] => high priority [1] => critical task [2] => medium task )
?>Try it yourself
<?php
// Read the JSON array of notifications
$jsonInput = fgets(STDIN);
$notifications = (array)json_decode($jsonInput, true);
// Read the urgent notification to add
$urgentNotification = trim(fgets(STDIN));
// TODO: Write your code below to add the urgent notification to the beginning of the array
// Output the final array
print_r($notifications);
?>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced Functions
Anonymous FunctionsClosures and 'use'Arrow FunctionsCallback FunctionsUsing 'call_user_func'Variable FunctionsPassing by ReferenceRecursive FunctionsRecap: Function Medley4Multi-dimensional Arrays
Creating a 2D ArrayAccessing 2D Array ElementsModifying 2D Array ElementsIterating with Nested Loops2D Associative ArraysRecap: Simple Grid Exercise2Advanced Array Manipulations
Adding with 'array_push'Removing with 'array_pop'Adding with 'array_unshift'Removing with 'array_shift'Merging Indexed ArraysMerging Associative ArraysExtracting with 'array_slice'Values with 'in_array'Keys with 'array_search'Recap: Playlist Exercise3Sorting Arrays
Sort Indexed Arrays AscendingSort Indexed Arrays DescendingSort Assoc Arrays by ValueSort Assoc Arrays by KeyNatural Order SortingCustom Sorting with 'usort'Recap: Leaderboard Sorting