Content · Web Development · PHP

PHP SplDoublyLinkedList::unshift() Method: Usage and Examples

Prepends an entry at the start of the list. Existing positions shift by one when a value is prepended.

1 views Published Oct 17, 2026 Updated Oct 17, 2026 admin

Prepends an entry at the start of the list.

The examples focus on the operation itself, including the important distinction: push appends a value at the end.

What It Does


Use the examples below to observe the behavior on a small dataset before extending it to application code.

Syntax and Return Value


SplDoublyLinkedList::unshift(mixed $value)

The displayed signature describes the API or identifies any correction or optional dependency. When a parameter is optional, supply it only when the task requires it.

Parameters


  • value: required.

Example 1: Basic Use


The list begins with 3 values. Notice how unshift changes or observes its indexed deque rather than an ordinary associative array.

<?php
$list = new SplDoublyLinkedList();
$list->push('tea');
$list->push('coffee');
$list->push('water');
$list->unshift('first');
echo json_encode(iterator_to_array($list));

Output from a successful local PHP 8.4 run:

["first","tea","coffee","water"]

Example 2: Checking Behavior


The list begins with 4 values. Notice how unshift changes or observes its indexed deque rather than an ordinary associative array.

<?php
$list = new SplDoublyLinkedList();
$list->push('one');
$list->push('two');
$list->push('three');
$list->push('four');
$list->unshift('zero');
echo json_encode(iterator_to_array($list));

Output from a successful local PHP 8.4 run:

["zero","one","two","three","four"]

Example 3: Practical Example


The list begins with 3 values. Notice how unshift changes or observes its indexed deque rather than an ordinary associative array.

<?php
$list = new SplDoublyLinkedList();
$list->push(4);
$list->push(8);
$list->push(12);
$list->unshift(0);
echo json_encode(iterator_to_array($list));

Output from a successful local PHP 8.4 run:

[0,4,8,12]

Important Behavior and Edge Cases


Existing positions shift by one when a value is prepended.

Comparison with Related Approaches


ApproachDifference
SplDoublyLinkedList::unshiftPrepends an entry at the start of the list.
Related API or alternativepush appends a value at the end.

Common Beginner Mistakes


MistakeCorrect approach
Ignoring the operation-specific limitsExisting positions shift by one when a value is prepended.
Confusing it with a related APIpush appends a value at the end.

Key Takeaways


  • Prepends an entry at the start of the list.
  • Existing positions shift by one when a value is prepended.
  • push appends a value at the end.

Use SplDoublyLinkedList::unshift when its documented behavior matches the problem. Test the relevant edge cases in your own runtime before deploying it.

Share this resourceSend this page to someone who may find it useful.