I have this array that I'm trying to process using a foreach
loop. And I need to call a function when the end of the array is reached. However, I have a problem determining when I have reached the end of the array.
Note: Because of the peculiar nature of what I'm working on, using a for
, while
or do ... while
loop does not come into the equation. I'm stuck with using a foreach
loop.
Also, if you are suggesting I use PHP's built-in end()
function, how do I do that? As the function returns the value at the end of the array. In my case, however, the value at the end of my array itself is an array, not a scalar value/variable.
Below is my code and attempts at determining the array's end.
$arr = array
(
0 => array
(
'departures' => array('date'=>'23 Feb', 'location'=>'Lagos'),
'returns' => array('date'=>'24 Feb', 'location'=>'Abuja')
),
1 => array
(
'departures' => array('date'=>'25 May', 'location'=>'Dubai'),
'returns' => array('date'=>'1 June', 'location'=>'New York')
),
3 => array
(
'departures' => array('date'=>'2 Apr', 'location'=>'Tokyo'),
'returns' => array('date'=>'6 Apr', 'location'=>'Seoul')
),
5 => array
(
'departures' => array('date'=>'2 Apr', 'location'=>''),
'returns' => array('date'=>'6 Apr', 'location'=>'')
),
2 => array
(
'departures' => array('date'=>'2 Apr', 'location'=>'LA'),
'returns' => array('date'=>'6 Apr', 'location'=>'California')
),
4 => array
(
'departures' => array('date'=>'2 Apr', 'location'=>''),
'returns' => array('date'=>'6 Apr', 'location'=>'Hong Kong')
),
);
$counter = 0;
$arr_size = count($arr);
foreach ($arr AS $curr_array)
{
$departures = $curr_array['departures'];
if( empty($departures['location']) )
{
continue;
}
if( $counter == ($arr_size - 1) )
{
//reached end of array, execute function
}
//process array
$counter++;
}
Any help will be greatly appreciated.
Don't make it complicated, this should work for you:
Here I first get the last key of your array, by getting all keys into an array with array_keys()
and then access the last element of the array == the last key of your array.
After this you can simply check in your foreach loop if the key is equals to the last one.
$end = array_keys($arr)[count($arr)-1];
foreach($arr as $k => $v) {
if($k == $end)
echo "last one!";
else
echo "still going!";
}
You can convert it to a sequential array for the loop
$array = array('banana', 'apple', 'orange', 'grape');
$size = count($array);
foreach(array_values($array) as $index => $fruit) {
if ($index === ($size - 1)) {
// Last element in the array
echo "The last fruit is {$fruit}";
} else {
echo $fruit.PHP_EOL;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.