How to use Array Keys In PHP
Using array keys, you can determine the first iteration in a foreach loop by checking if the current key matches the first key of the array. Similarly, you identify the last iteration by comparing the current key with the last key of the array.
Example:
<?php
// Nikunj Sonigara
// Declare an array and initialize it
$myarray = array(1, 2, 3, 4, 5, 6);
// Get the first and last keys of the array
$firstKey = array_key_first($myarray);
$lastKey = array_key_last($myarray);
// Loop starts here
foreach ($myarray as $key => $item) {
// Check if the current key is the first key
if ($key == $firstKey) {
print($item);
print(": First iteration \n");
}
// Check if the current key is the last key
if ($key == $lastKey) {
print($item);
print(": Last iteration \n");
}
}
?>
Output
1: First iteration 6: Last iteration
Determine the first and last iteration in a foreach loop in PHP?
Given an array of elements and the task is to determine the first and last iteration in the foreach loop. There are many ways to solve this problem which are listed below:
Table of Content
- Naive method
- Using reset and end function
- Using reset() function
- Using Array Keys