关于PHP的一个小题目:
- <?php
- $arr = array(1,2,3);
- foreach($arr as $num) {
- if ($num == 2) $arr[] = 4;
- echo $num;
- }
|
<?php $arr = array(1,2,3); foreach($arr as $num) { if ($num == 2) $arr[] = 4; echo $num; } |
输出结果: 1234 还是 123 ?
答案: 123
如果才能达到 1234 的效果呢?
使用list、each, 代码如下:
- <?php
- $arr = array(1,0,null,2,3);
- while(list($key, $num) = each($arr)) {
- if ($num == 2) $arr[] = 4;
- echo $num;
- }
|
<?php $arr = array(1,0,null,2,3); while(list($key, $num) = each($arr)) { if ($num == 2) $arr[] = 4; echo $num; } print_r($arr); |