dqhr76378 2014-05-27 01:34
浏览 7
已采纳

使用While重写PHP代码片段,每个列表可以使用Foreach或更简单的方式[关闭]

I have following code snippet but i dont understand what its do, but i think there is easy way to write this code again with a simple foreach like below, is that correct ?

        $paypal_message="";
while( @list($key,$value) = @each($paypal_post_vars)) {
    $paypal_message .= $key.":\t".$value."
";
    if($key!='custom'){
        $insert_sql.=" `".$key."`='".$value."' , ";     
    }
 }

I think rewrite it like this ? is it exactly the same ?

foreach($paypal_post_vars as $key=>$value ){

    $paypal_message .= $key.":\t".$value."
";

    if($key!='custom'){
            $insert_sql.=" `".$key."`='".$value."' , ";     
        }

}
  • 写回答

1条回答 默认 最新

  • dpl9717 2014-05-27 02:08
    关注

    Yes, this is functionally identical code, if you look at php site - control structures foreach have the explanation below

    You may have noticed that the following are functionally identical:

    <?php
    $arr = array("one", "two", "three");
    reset($arr);
    while (list(, $value) = each($arr)) {
        //     ^^ supressing key
        echo "Value: $value<br />
    ";
    }
    
    foreach ($arr as $value) {
        echo "Value: $value<br />
    ";
    }
    

    The following are also functionally identical:

    <?php
    $arr = array("one", "two", "three");
    reset($arr);
    while (list($key, $value) = each($arr)) {
        echo "Key: $key; Value: $value<br />
    ";
    }
    
    foreach ($arr as $key => $value) {
        echo "Key: $key; Value: $value<br />
    ";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 vscode的问题提问
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM