Line 3 of the code below fails if I omit the => $v portion. I get the following error:
Warning: Illegal offset type in /home/site/page.php on line 404
When the [$k] in line 5 is changed to ['$k'], i receive the following error.
Notice: Undefined index: $k in /home/site/page.php on line 404
When it is like below with the the full $k => $v everything works though. I don’t even use $v. Why do I need it in the foreach loop to make it work then?
<? if ( $arr[ 'status'][ 'chain'] ) {
foreach ( $arr[ 'status'][ 'chain'] as $k => $v) { ?>
<tr>
<td class="line_item_data status_td">
<?= $ arr[ 'status'][ 'chain'][$k][ 'message'] ?>
</td>
<td align="center">
<img src="images/green_check.gif" width="20" />
</td>
</tr>
<? }
} ?>
I did see this answer, but don’t know that it really applies. Thanks so much!
The construct
$k => $vis used to iterate an array’s keys and values in aforeachconstruct. You can iterate using the values$valone, but you cannot iterate over the keys alone$k. If you used the following:…the foreach loop is syntactically valid but
$kwould be populated with the array value rather than the key. In that case, the array element$ arr[ 'status'][ 'chain'][$k][ 'message']does not exist since$kdoes not hold a key valid in the array$arr['status']['chain'].However, this can be much simpler…
Inside the loop,
$vholds the array element you are attempting to index, so you merely need to access it as:That is the equivalent of
$arr['status']['chain'][$k]['message']. So ultimately it isn’t$vthat you don’t need in your loop, but rather it is$kyou don’t need.