Two arrays in foreach loop

后端 未结 22 1765
不思量自难忘°
不思量自难忘° 2020-11-22 04:48

I want to generate a selectbox using two arrays, one containing the country codes and another containing the country names.

This is an example:

22条回答
  •  一整个雨季
    2020-11-22 05:36

    foreach only works with a single array. To step through multiple arrays, it's better to use the each() function in a while loop:

    while(($code = each($codes)) && ($name = each($names))) {
        echo '';
    }
    

    each() returns information about the current key and value of the array and increments the internal pointer by one, or returns false if it has reached the end of the array. This code would not be dependent upon the two arrays having identical keys or having the same sort of elements. The loop terminates when one of the two arrays is finished.

提交回复
热议问题