note 127869 added to class.arrayiterator
| From: | butesa at freenet dot de | Date: | Fri, 28 Oct 2022 17:11:57 +0000 |
| Subject: | note 127869 added to class.arrayiterator | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-219821@lists.php.net to get a copy of this message | ||
The documentation states "This iterator allows to unset and modify values and keys while
iterating over Arrays and Objects". But if you pass an array to the constructor, the iterator
works with a copy of that array, so the modifications will not be written back to that initial
array. ArrayObject behaves the same way.
If you want an iterator that writes back to the array, you can use this function:
<?php
function &getArrayIterator(array &$a): Iterator {
foreach ($a as $k => &$v) {
yield $k => $v;
}
}
?>
Usage:
<?php
$array = [1 => 'a', 2 => 'b'];
$iterator = getArrayIterator($array);
foreach ($iterator as &$value) {
$value .= 'x';
}
//array(2) {
// [1]=>
// string(2) "ax"
// [2]=>
// &string(2) "bx"
//}
//object(Generator)#4 (0) {
//}
var_dump($array);
var_dump($iterator);
?>
Comparison with plain array, ArrayIterator and ArrayObject:
<?php
$array1 = [1 => 'a', 2 => 'b'];
$array2 = [1 => 'a', 2 => 'b'];
$array3 = [1 => 'a', 2 => 'b'];
foreach ($array1 as &$value) {
$value .= 'x';
}
$iterator2 = new ArrayIterator($array2);
foreach ($iterator2 as &$value) {
$value .= 'x';
}
$iterator3 = new ArrayObject($array3);
foreach ($iterator3 as &$value) {
$value .= 'x';
}
//array(2) {
// [1]=>
// string(2) "ax"
// [2]=>
// string(2) "bx"
//}
var_dump($array1);
//array(2) {
// [1]=>
// string(1) "a"
// [2]=>
// string(1) "b"
//}
//object(ArrayIterator)#1 (1) {
// ["storage":"ArrayIterator":private]=>
// array(2) {
// [1]=>
// string(2) "ax"
// [2]=>
// string(2) "bx"
// }
//}
var_dump($array2);
var_dump($iterator2);
//array(2) {
// [1]=>
// string(1) "a"
// [2]=>
// string(1) "b"
//}
//object(ArrayObject)#2 (1) {
// ["storage":"ArrayObject":private]=>
// array(2) {
// [1]=>
// string(2) "ax"
// [2]=>
// string(2) "bx"
// }
//}
var_dump($array3);
var_dump($iterator3);
?>
----
Server IP: 45.112.84.4
Probable Submitter: 45.91.159.161 (proxied: 89.247.163.235)
----
Manual Page -- https://php.net/manual/en/class.arrayiterator.php
Edit -- https://main.php.net/note/edit/127869
Del: integrated -- https://main.php.net/note/delete/127869/integrated
Del: useless -- https://main.php.net/note/delete/127869/useless
Del: bad code -- https://main.php.net/note/delete/127869/bad+code
Del: spam -- https://main.php.net/note/delete/127869/spam
Del: non-english -- https://main.php.net/note/delete/127869/non-english
Del: in docs -- https://main.php.net/note/delete/127869/in+docs
Del: other reasons-- https://main.php.net/note/delete/127869
Reject -- https://main.php.net/note/reject/127869
Search -- https://main.php.net/manage/user-notes.php