Reputation: 103
How to work out the stack if we use push and add together
$stack = new SplStack();
$stack[] = 'one2';
$stack[] = 20152;
$stack[] = 'two2';
echo "<pre>";
print_r($stack);
$stack->add(0, 'one');
$stack->add(1, 'two');
$stack->add(2, '2015');
echo "<pre>";
print_r($stack);
I am seeing this in the result but could not get my head to work out the second section.
Result of first print_r:
SplStack Object
(
[flags:SplDoublyLinkedList:private] => 6
[dllist:SplDoublyLinkedList:private] => Array
(
[0] => one2
[1] => 20152
[2] => two2
)
)
Result of second print_r:
SplStack Object
(
[flags:SplDoublyLinkedList:private] => 6
[dllist:SplDoublyLinkedList:private] => Array
(
[0] => one2
[1] => 20152
[2] => 2015
[3] => two
[4] => one
[5] => two2
)
)
Upvotes: 0
Views: 192
Reputation: 147206
It took me a while to get my head around it too, but the behaviour is correct. It is better to look at the list by using the list indexes, rather than a print_r
of the internal array. This code will do that:
for ($i = 0; $i < $stack->count(); $i++) {
echo "index $i contains " . $stack->offsetGet($i) . "\n";
}
Note that index 0 represents the top of the list (i.e. what would be returned by $stack->pop()
). This is what it looks like after your initial block of code:
index 0 contains two2
index 1 contains 20152
index 2 contains one2
This is because $stack[] = x
is equivalent to $stack->push(x)
.
Now looking at your next block of code:
$stack->add(0, 'one');
If we look at the manual for add
, it says:
Insert the value newval at the specified index, shuffling the previous value at that index (and all subsequent values) up through the list.
Since the top of the list is index 0, the value in the add has to be inserted at index 1 so that the existing value at index 0 can be "shuffled up through the list" i.e. it has to remain at index 0. Thus after this code is executed a dump of the list shows this:
index 0 contains two2
index 1 contains one
index 2 contains 20152
index 3 contains one2
The same thing happens with the other add
s, they have to go at the next index down so that the values ahead of them in the list stay that way. Thus after the two other adds the list looks like:
index 0 contains two2
index 1 contains one
index 2 contains two
index 3 contains 2015
index 4 contains 20152
index 5 contains one2
And if you try to pop everything off the stack:
while ($stack->count()) {
echo $stack->pop() . "\n";
}
You get:
two2
one
two
2015
20152
one2
Note: if you want to add a value to the very top of the list you have to use unshift(value)
.
Upvotes: 2