[php-src] Issue #9168: SplStack useless?

From: Date: Wed, 27 Jul 2022 14:21:01 +0000
Subject: [php-src] Issue #9168: SplStack useless?
Groups: php.bugs 
Request: Send a blank email to php-bugs+get-242042@lists.php.net to get a copy of this message
Issue: https://github.com/php/php-src/issues/9168 Author: 6562680 ### Description The following code: ```php $tree = [ '' => function () { return [ 1 ]; }, 1 => function () { return [ 2, 3, 4 ]; }, 2 => function () { return [ 5, 6 ]; }, 3 => function () { return [ 7, 8 ]; }, ]; $stack = new \SplStack(); $stack->push([ '', 0 ]); while ( ! $stack->isEmpty() ) { [ $parent, $level ] = $stack->pop(); echo str_repeat(' ', $level - 1) . $parent . PHP_EOL; $children = isset($tree[ $parent ]) ? $tree[ $parent ]() : []; foreach ( array_reverse($children) as $child ) { $stack->push([ $child, $level + 1 ]); } } ``` Resulted in this output: ``` // 1 // 2 // 5 // 6 // 3 // 7 // 8 // 4 ``` But I expected this output instead: ``` ? ``` Stack should inverse push() / pop() methods, but instead push()/pop() works with internal DoubleLinkedList and works as plain array. It means SplStack works only with ->rewind() and then ->current() / ->next() / ->prev() than makes it useless if we need push to stack in each step. Or i just cant imagine how to do that. Look, in my code children becomes to stack LATER; What is actually works as "stack" is this code: ``` /** * @param mixed $item * * @return \Generator */ function stack($item) : \Generator { $stack = [ $item ]; while ( $item = array_pop($stack) ) { yield $item; $children = yield; $keys = array_keys($children); foreach ( array_reverse($keys) as $i ) { $stack[] = $children[ $i ]; } } } $generator = stack(''); while ($generator->valid()) { [ $parent, $level ] = $generator->current(); $children = isset($tree[ $parent ]) ? $tree[ $parent ]() : []; $generator->send($children); } ``` I've just tried to make generator code shorter using SplStack and get it unsolvable. ### PHP Version PHP 7.3 ### Operating System Windows 10

« previous php.bugs (#242042) next »