|
-
Mar 11th, 2013, 09:26 AM
#1
Thread Starter
Hyperactive Member
Find the last non zero value in an array
How to do it get the last non zero value of an array?
I want to learn more 
grace 
-
Mar 11th, 2013, 11:50 AM
#2
Re: Find the last non zero value in an array
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! } }
?>
If my post was helpful to you, then express your gratitude using Rate this Post. 
And if your problem is SOLVED, then please Mark the Thread as RESOLVED (see it in action - video)
My system: AMD FX 6100, Gigabyte Motherboard, 8 GB Crossair Vengance, Cooler Master 450W Thunder PSU, 1.4 TB HDD, 18.5" TFT(Wide), Antec V1 Cabinet
Social Group: VBForums - Developers from India
Skills: PHP, MySQL, jQuery, VB.Net, Photoshop, CodeIgniter, Bootstrap,...
-
Mar 11th, 2013, 07:26 PM
#3
Thread Starter
Hyperactive Member
Re: Find the last non zero value in an array
thanks i will try that
I want to learn more 
grace 
-
Mar 12th, 2013, 07:05 PM
#4
Re: Find the last non zero value in an array
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; }
-
Mar 14th, 2013, 06:32 AM
#5
Re: Find the last non zero value in an array
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
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|