note 126700 added to control-structures.foreach
| From: | HenrikSchmidt at main dot php dot net | Date: | Tue, 21 Dec 2021 09:20:45 +0000 |
| Subject: | note 126700 added to control-structures.foreach | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-217397@lists.php.net to get a copy of this message | ||
It seems there is no easy way of itterating large arrays inplace.
Solutions uses temporary key arrays anddo array reverse and so on, not a good fit for me with 170
000items in the array.
I wrote this solution but I really wish someone will give me a better solution. (the callback step
is optional of course)
ArrayIterator first needed to make an array object copy of the array, so that was of no use.
<?php
$a = [10,20,30,40,50,60,70,80];
function foreachrev( array &$a, callable $funct ) : void
{
for( end( $a ) ; current( $a )!==false ; prev( $a ) )
{
$key = key( $a );
$funct( $key, $a[$key] );
}
}
$sum = 0;
foreachrev( $a, function( $key, &$val ) use(&$sum)
{
$sum+=$val;
$val=($sum);
} );
print_r( $a );
print_r( $sum );
?>
----
Server IP: 45.112.84.4
Probable Submitter: 80.90.5.135 (proxied: 185.176.246.186)
----
Manual Page -- https://php.net/manual/en/control-structures.foreach.php
Edit -- https://main.php.net/note/edit/126700
Del: integrated -- https://main.php.net/note/delete/126700/integrated
Del: useless -- https://main.php.net/note/delete/126700/useless
Del: bad code -- https://main.php.net/note/delete/126700/bad+code
Del: spam -- https://main.php.net/note/delete/126700/spam
Del: non-english -- https://main.php.net/note/delete/126700/non-english
Del: in docs -- https://main.php.net/note/delete/126700/in+docs
Del: other reasons-- https://main.php.net/note/delete/126700
Reject -- https://main.php.net/note/reject/126700
Search -- https://main.php.net/manage/user-notes.php