Results 1 to 5 of 5

Thread: Find the last non zero value in an array

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Nov 2004
    Location
    San Isidro
    Posts
    326

    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

  2. #2
    Freelancer akhileshbc's Avatar
    Join Date
    Jun 2008
    Location
    Trivandrum, Kerala, India
    Posts
    7,652

    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,...

  3. #3

    Thread Starter
    Hyperactive Member
    Join Date
    Nov 2004
    Location
    San Isidro
    Posts
    326

    Re: Find the last non zero value in an array

    thanks i will try that
    I want to learn more
    grace

  4. #4
    I'm about to be a PowerPoster!
    Join Date
    Jan 2005
    Location
    Everywhere
    Posts
    13,647

    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>= 0; --i)
        if (
    $list[$i] !== 0)
          return 
    $list[$i];
      return 
    null;


  5. #5
    WiggleWiggle dclamp's Avatar
    Join Date
    Aug 2006
    Posts
    3,527

    Re: Find the last non zero value in an array

    Why not just use built in functions?

    PHP Code:
    $array = array(025730461009000);

    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
  •  



Click Here to Expand Forum to Full Width