Inserts a value at a specified zero-based position, shifting later elements toward the end.
The examples focus on the operation itself, including the important distinction: push appends; add inserts at a specified position.
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::add(int $index, 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
- index: required.
- value: required.
Example 1: Basic Use
The list begins with 3 values. Notice how add 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->add(1, 'milk');
echo json_encode(iterator_to_array($list));
Output from a successful local PHP 8.4 run:
["tea","milk","coffee","water"]
Example 2: Checking Behavior
The list begins with 4 values. Notice how add 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->add(1, 'extra');
echo json_encode(iterator_to_array($list));
Output from a successful local PHP 8.4 run:
["one","extra","two","three","four"]
Example 3: Practical Example
The list begins with 3 values. Notice how add 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->add(2, 10);
echo json_encode(iterator_to_array($list));
Output from a successful local PHP 8.4 run:
[4,8,10,12]
Important Behavior and Edge Cases
An out-of-range index raises OutOfRangeException; use push to append at the end.
Comparison with Related Approaches
| Approach | Difference |
|---|---|
| SplDoublyLinkedList::add | Inserts a value at a specified zero-based position, shifting later elements toward the end. |
| Related API or alternative | push appends; add inserts at a specified position. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Ignoring the operation-specific limits | An out-of-range index raises OutOfRangeException; use push to append at the end. |
| Confusing it with a related API | push appends; add inserts at a specified position. |
Key Takeaways
- Inserts a value at a specified zero-based position, shifting later elements toward the end.
- An out-of-range index raises OutOfRangeException; use push to append at the end.
- push appends; add inserts at a specified position.
Use SplDoublyLinkedList::add when its documented behavior matches the problem. Test the relevant edge cases in your own runtime before deploying it.