You can use PHP end ()
$array = array('a' => 1,'b' => 2,'c' => 3); $lastElement = end($array); foreach($array as $k => $v) { echo $v . '<br/>'; if($v == $lastElement) {
Update1
as @Mijoja pointed out, the above can have problems if you have the same value several times in the array. below is the fix.
$array = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 2); //point to end of the array end($array); //fetch key of the last element of the array. $lastElementKey = key($array); //iterate the array foreach($array as $k => $v) { if($k == $lastElementKey) { //during array iteration this condition states the last element. } }
Update2
I found that @onteria_'s solution turned out to be better than what I answered, since it does not change the internal pointer of arrays, I am updating the answer so that it matches his answer.
$array = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 2); // Get array keys $arrayKeys = array_keys($array); // Fetch last array key $lastArrayKey = array_pop($arrayKeys); //iterate array foreach($array as $k => $v) { if($k == $lastArrayKey) { //during array iteration this condition states the last element. } }
Thanks @onteria_
Update3
As pointed out by @CGundlach, array_key_last was introduced in PHP 7.3, which seems like a much better option if you use PHP> = 7.3
$array = array('a' => 1,'b' => 2,'c' => 3); $lastKey = array_key_last($array); foreach($array as $k => $v) { echo $v . '<br/>'; if($k == $lastKey) {
Ibrahim Azhar Armar May 23 '11 at 1:54 a.m. 2011-05-23 01:54
source share