Retrieve Array Keys During Foreach Loop: PHP
When working with arrays in PHP, it's often necessary to retrieve both the keys and values within a foreach loop. The key() function provides a convenient way to access the current key during the iteration. However, in certain scenarios, it may not yield the desired result.
Consider the following code that aims to generate an HTML table from the sample array:
<code class="php">foreach($samplearr as $item){ print "<tr\><td>" . key($item) . "</td>\><td>" . $samplearr['value1'] . "</td>\><td>" . $samplearr['value2'] . "</td>\></tr\>"; }</code>
This code incorrectly returns the key as "value1" instead of the actual key of the outer array (e.g., 4722).
To resolve this issue, it's necessary to use the array key as the iteration variable:
<code class="php">foreach($samplearr as $key => $item){ print "<tr\><td>" . $key . "</td>\><td>" . $item['value1'] . "</td>\><td>" . $item['value2'] . "</td>\></tr\>"; }</code>
By declaring the loop variable as "$key," you can directly access the key of the outer array within the loop. This code will now correctly generate the expected HTML table:
<code class="html"><tr\><td>4722</td>\><td>52</td>\><td>46</td>\></tr\> <tr\><td>4922</td>\><td>22</td>\><td>47</td>\></tr\> <tr\><td>7522</td>\><td>47</td>\><td>85</td>\></tr\></code>
위 내용은 PHP의 Foreach 루프 내에서 배열 키를 검색하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!