PHP: Retrieving Array Keys in Foreach Loop
In PHP, iterating over an associative array using the foreach loop provides access to both the values and keys. However, the key() function only returns the current value's key, which can be insufficient when working with nested arrays.
For instance, consider an array like this:
array('value1' => 52, 'value2' => 46),
4922 => array('value1' => 22, 'value2' => 47),
7522 => array('value1' => 47, 'value2' => 85)
);
?>
If you attempt to use key($item) in a foreach loop to retrieve the parent key, you may encounter unexpected results:
" . key($item) . " ";
echo "" . $samplearr['value1'] . " ";
echo "" . $samplearr['value2'] . " ";
}
?>
This code only returns the value keys: value1 and value2.
To access the parent keys, you can use the following approach in the foreach loop:
$item) {
echo "" . $key . " ";
echo "" . $item['value1'] . " ";
echo "" . $item['value2'] . " ";
}
?>
By using $key, the loop iterates over the parent keys, allowing you to access and print both the parent and child values as desired.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3