Created
June 22, 2012 02:51
-
-
Save pjxiao/2969920 to your computer and use it in GitHub Desktop.
Inner pointer of an array is reset when it is copied.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
* 配列をコピーすると内部ポインタがリセットされるテスト | |
* TEST: Inner pointer of an array is reset when it is copied. | |
* | |
* foreach は最初に配列全体をメモリに展開するから、 | |
* while のが省メモリとかいう話を聞いた気がした。 | |
* そこで、while でループ回してたら無限ループにハマったのでメモ。 | |
* Because 'foreach' locate all of array on memory, | |
* 'while' use lower memory. | |
* I try to use 'while' but go into an infinite loop. | |
*/ | |
// 配列 | |
$arr = array('hoge', 'fuga', 'foo', 'bar'); | |
// コピー先配列 | |
$arr_cp = null; | |
// 配列長 | |
$len = count($arr); | |
// カウンタ | |
$i = 0; | |
while ((list($k, $v) = each($arr)) && $i < $len) { | |
// 配列をコピーする | |
$arr_cp = $arr; | |
printf('%0d $k: %s, $v: %s'."\n", $i, $k, $v); | |
$i++; | |
} | |
unset($k, $v); | |
reset($arr); | |
$i = 0; | |
echo 'foreach'."\n"; | |
foreach ($arr as $k => $v) { | |
// 配列をコピーする | |
$arr_cp = $arr; | |
printf('%0d $k: %s, $v: %s'."\n", $i, $k, $v); | |
$i++; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
while
0 $k: 0, $v: hoge
1 $k: 0, $v: hoge
2 $k: 0, $v: hoge
3 $k: 0, $v: hoge
foreach
0 $k: 0, $v: hoge
1 $k: 1, $v: fuga
2 $k: 2, $v: foo
3 $k: 3, $v: bar