dt250827 2016-02-11 13:44
浏览 99
已采纳

Foreach循环两个不相等的数组

I know how to loop through equal arrays like this

foreach( $codes as $index => $code ) {
   echo 'The Code is '.$code;
   echo 'The Name is '.$names[$index];
}

Not sure how to loop through these 2 arrays and still manage to get all values when both arrays have different number of elements.

$code = array(R9,R10,R11,R12);

$names = array(Robert,John,Steve,Joe,Eddie,Gotham);
  • 写回答

1条回答 默认 最新

  • doubao6681 2016-02-11 14:13
    关注

    ...how to loop through these 2 arrays and still manage to get all values when both arrays have different number of elements.

    You can use for loop for this.

    The solution is:

    • Take length of the longest array as the condition for for loop.
    • Use array_key_exists() function to check whether the index exists in the particular array or not, and display the element accordingly.

    So your code should be like this:

    $code = array("R9","R10","R11","R12");
    $names = array("Robert","John","Steve","Joe","Eddie","Gotham");
    
    $maxLength = count($code) > count($names) ? count($code) : count($names);
    
    for($i = 0; $i < $maxLength; ++$i){
        echo array_key_exists($i, $code) ? 'The Code is '. $code[$i] : "";
        echo array_key_exists($i, $names) ? ' The Name is '. $names[$i] : "";
        echo "<br />";
    }
    

    Output:

    The Code is R9 The Name is Robert
    The Code is R10 The Name is John
    The Code is R11 The Name is Steve
    The Code is R12 The Name is Joe
    The Name is Eddie
    The Name is Gotham
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

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