Req #80120 [Opn->Fbk]: ForEach() backwards support?

From: Date: Fri, 18 Sep 2020 16:20:06 +0000
Subject: Req #80120 [Opn->Fbk]: ForEach() backwards support?
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-229076@lists.php.net to get a copy of this message
Edit report at https://bugs.php.net/bug.php?id=80120&edit=1 ID: 80120 Updated by: requinix@php.net Reported by: divinity76 at gmail dot com Summary: ForEach() backwards support? -Status: Open +Status: Feedback Type: Feature/Change Request Package: *General Issues PHP Version: Next Minor Version Block user comment: N Private report: N New Comment: For one, this isn't going to work with iterators. Those can only run in one direction. But I'm not sure why this needs to be a feature. It's not hard to set up for loops on arrays, and with iterators there's iterator_to_array + array_reverse (if you know it's safe to do so). Is there a case where it's "too hard" to do it in reverse manually? Previous Comments: ------------------------------------------------------------------------ [2020-09-18 08:33:26] divinity76 at gmail dot com Description: ------------ There are situations where one want to iterate a list backwards, I was recently in such a situation, writing: <?php $removeWhitespaceTextNodes = function (\DOMNode $node) use (&$removeWhitespaceTextNodes): void { if ($node->hasChildNodes()) { // Warning: it's important to do it backwards; if you do it forwards, the index for DOMNodeList might become invalidated; // that's why i don't use ForEach() - don't change it (unless you know what you're doing, ofc) for ($i = $node->childNodes->length - 1; $i >= 0; --$i) { $removeWhitespaceTextNodes($node->childNodes->item($i)); } } if ($node->nodeType === XML_TEXT_NODE && !$node->hasChildNodes() && !$node->hasAttributes() && (strlen(trim($node->textContent)) === 0)) { $node->parentNode->removeChild($node); } }; ?> I think it could be useful if ForEach() could iterate stuff backwards, maybe something like: <?php ForEach($iterable as $index=>$val, $flags = 0){} ?> (with a new FOREACH_BACKWARDS flag) or maybe just <?php ForEach($iterable as $index=>$val, bool $backwards = false){} ?> or something like that? ------------------------------------------------------------------------ -- Edit this bug report at https://bugs.php.net/bug.php?id=80120&edit=1

« previous php.bugs (#229076) next »