How to do it get the last non zero value of an array?
Printable View
How to do it get the last non zero value of an array?
:wave:PHP Code:<?php
$myarr = array(1,0,22,3,85,69,0,11,2,0,0); //sample array
$t = array_reverse($myarr); //reverses the array
foreach($t as $ele) //loop through the elements in array
{
if($ele > 0) //if the element is greater than 0...
{
echo 'Last non-zero number = ' . $ele; //gives 2 as answer
break; // no need to continue the loop since we found an item!
}
}
?>
thanks :) i will try that :)
No need to reverse the array...
PHP Code:function lastNonZero($list)
{
for ($i = count($list) - 1; i >= 0; --i)
if ($list[$i] !== 0)
return $list[$i];
return null;
}
Why not just use built in functions?
PHP Code:$array = array(0, 2, 5, 7, 3, 0, 4, 6, 1, 0, 0, 9, 0, 0, 0);
echo end(array_filter($array));
// Returns 9