PHP array_unshift() Function

PHP

PHP array_unshift() - Add Elements to Beginning

SEO Description: Learn PHP array_unshift() function. Add one or more elements to the beginning of an array.

Introduction

In PHP, arrays are one of the most fundamental data structures for managing collections of elements. When working with arrays, you might often need to add elements to the beginning rather than the end. This is where the array_unshift() function becomes extremely useful. It allows you to prepend one or more elements to the start of an existing array. This tutorial will guide you step-by-step on how to use array_unshift(), its syntax, behavior regarding reindexing existing elements, common mistakes to avoid, and interview questions to prepare you for coding interviews.

Prerequisites

  • Basic knowledge of PHP programming.
  • Familiarity with PHP arrays and their structure.
  • A working PHP development environment (PHP 5.0+ recommended).

Setup Steps

  1. Install PHP on your machine. You can download it from php.net.
  2. Set up a local web server environment such as XAMPP, WAMP, or MAMP, or use the built-in PHP server.
  3. Create a PHP script file (e.g., array_unshift_example.php) to try out the function.
  4. Run the script through your server or command line interface (CLI).

What is array_unshift()?

array_unshift() is a built-in PHP function designed to add one or more elements to the beginning of an array. After prepend operation, the existing elements inside the array are reindexed if the array is indexed numerically.

Syntax

int array_unshift(array &$array, mixed $value1 [, mixed $value2 [, mixed $... ]])
  • $array: The input array passed by reference.
  • $value1, $value2, ...: One or more values to prepend to the array.
  • Returns the new number of elements in the array.

Examples Explained

Example 1: Adding one element to the beginning

<?php
$array = [2, 3, 4];
array_unshift($array, 1);
print_r($array);
?>

Output:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)

Explanation: The element 1 was added to the beginning, and the array keys were reindexed starting from 0.

Example 2: Adding multiple elements to the beginning

<?php
$fruits = ['apple', 'banana'];
array_unshift($fruits, 'orange', 'mango');
print_r($fruits);
?>

Output:

Array
(
    [0] => orange
    [1] => mango
    [2] => apple
    [3] => banana
)

Explanation: Both 'orange' and 'mango' are prepended in the order they are provided.

Example 3: Effect on associative arrays

<?php
$assoc = ['a' => 'apple', 'b' => 'banana'];
array_unshift($assoc, 'orange');
print_r($assoc);
?>

Output:

Array
(
    [0] => orange
    [a] => apple
    [b] => banana
)

Explanation: When you use array_unshift() on an associative array, the numeric key 0 is reserved for the prepended value, and the original keys remain unchanged.

Example 4: Numeric array reindexing

<?php
$numbers = [10 => 'ten', 20 => 'twenty'];
array_unshift($numbers, 'zero');
print_r($numbers);
?>

Output:

Array
(
    [0] => zero
    [10] => ten
    [20] => twenty
)

Explanation: Keys are not reindexed for numeric associative arrays with explicit keys; the prepended element gets the key 0.

Best Practices

  • Use array_unshift() when you specifically need to add elements to the front of an array.
  • Remember that array_unshift() reindexes numeric arrays starting at 0, which might impact loops iteration based on keys.
  • For associative arrays, be mindful that prepended elements get numeric keys starting from zero, potentially mixing key types.
  • When performance matters and multiple insertions are expected, consider array merging or other data structures as array_unshift() can be costly on large arrays due to reindexing.
  • Always pass arrays by reference since the function modifies the original array.

Common Mistakes

  • Expecting keys to remain same on numeric arrays: array_unshift() reindexes numeric arrays starting at zero, which can lead to unexpected results if you rely on original keys.
  • Using it on non-array variables: The function requires an array parameter and will produce warnings or errors otherwise.
  • Confusing array_unshift() with array_push(): array_unshift() adds at the beginning, array_push() adds at the end.
  • Not handling references properly in function calls: Because the array is modified in place, do not assign the return value expecting the new array but rather use the original variable.

Interview Questions

Junior-level Questions

  • Q1: What does array_unshift() do in PHP?
    A1: It adds one or more elements to the beginning of an array, shifting other elements forward.
  • Q2: Does array_unshift() work on associative arrays?
    A2: Yes, but prepended values get numeric keys starting from 0.
  • Q3: What is returned by the array_unshift() function?
    A3: The new number of elements in the array after insertion.
  • Q4: Will the keys of a numeric array be preserved after using array_unshift()?
    A4: No, numeric keys will be reindexed starting from 0.
  • Q5: How do you add multiple elements at the beginning of an array?
    A5: Pass multiple values as additional parameters to array_unshift().

Mid-level Questions

  • Q1: Explain the difference in behavior of array_unshift() when used on indexed vs associative arrays.
    A1: Indexed arrays are reindexed starting at 0, whereas associative arrays keep existing keys but newly prepended elements get numeric keys.
  • Q2: Can array_unshift() cause performance issues in PHP? If yes, why?
    A2: Yes, because it reindexes the array and shifts all elements, which can be costly for large arrays.
  • Q3: How can you add an element at the beginning of an array without reindexing its keys?
    A3: In practice, using array_unshift() always reindexes numeric arrays; to avoid reindexing, you can create a new array and use array union (+) operator for associative keys.
  • Q4: What happens if you provide a non-array as the first argument to array_unshift()?
    A4: PHP generates a warning/error because the first argument must be an array passed by reference.
  • Q5: How can you prepend an element to an array and keep original numeric indexes intact?
    A5: You can assign the new element with a key manually before existing elements, but this does not shift others; careful array manipulation is necessary instead of using array_unshift().

Senior-level Questions

  • Q1: Describe the internal mechanism of array_unshift() in PHP for numeric arrays.
    A1: PHP shifts all existing elements one or more positions forward, inserts new elements at the start, and reindexes numeric keys sequentially from 0.
  • Q2: How does array_unshift() affect memory allocation in PHP arrays?
    A2: Because PHP arrays are hash tables, shifting elements involves reallocating keys and values internally, which may increase memory overhead temporarily.
  • Q3: Is array_unshift() stable regarding element ordering when adding multiple elements?
    A3: Yes, the elements are prepended in the order they are passed, preserving their relative order at the front.
  • Q4: How might you optimize prepend operations if you need frequent insertions at the start of a large array?
    A4: Use data structures like SplDoublyLinkedList or maintain two separate arrays for front and back and merge when necessary to avoid costly reindexing.
  • Q5: Can you manipulate array_unshift() behavior to prevent mixing numeric and associative keys? Suggest an approach.
    A5: Rather than using array_unshift() directly, manually build a new associative array and merge it with the existing one using the union operator to control key types.

FAQ

Can array_unshift() add elements to an empty array?
Yes, it can prepend elements to an empty array, making those elements the array’s first items.
Is the original array modified after array_unshift() is called?
Yes, the function modifies the original array by reference.
What happens if I use array_unshift() on an object instead of an array?
PHP will raise a warning or an error because the first parameter must be an array.
Can I use array_unshift() to add an array as the first element?
Yes, you can prepend an array as a single element, resulting in a nested array.
Does array_unshift() preserve original keys in associative arrays?
Yes, existing associative keys remain unchanged, but newly added elements get numeric keys starting at 0.

Conclusion

The PHP array_unshift() function is an essential tool when you need to add elements to the beginning of an array quickly and effectively. It works well in both indexed and associative array contexts, though it behaves differently regarding keys and reindexing. Understanding its mechanics, best practices, and caveats such as the reindexing of numeric keys will help you avoid common pitfalls and write more predictable PHP code. Whether in day-to-day PHP scripting or preparing for technical interviews, mastering array_unshift() enhances your array management skills.