Page 1 of 1

Array Function Needed - Find count of "Groupings"

Posted: Sun Aug 22, 2010 5:32 pm
by HappyJupiter
Hello all!

I'd like to find a nice neat way of checking if an array has one "grouping" of values or more than one "grouping" of values (or no groupings at all). I need help building a function to do this. (I could do this with looping and lots of variables, but I'm hoping that I'm just forgetting about some really handy php array functions :)

examples:

#1
$my_array=array(0,0,1,1,1,0,0,0);
$result=multiple($my_array);

$result would equal 1 since there is one group of values together without gaps (zero/null values)

#2
array(0,0,1,1,1,0,1,0);
$result=multiple($my_array);

$result would equal 2 since there is two groups of values together without gaps (zero/null values)


#3
array(0,0,0,0,0,0,0,0);
$result=multiple($my_array);

$result would equal 0 since there are no groups of values together without gaps (zero/null values)


Any help would be wonderful! Thanks in advance!

Re: Array Function Needed - Find count of "Groupings"

Posted: Sun Aug 22, 2010 6:30 pm
by MindOverBody
Here you are, i think this is what you want :wink:

Code: Select all

function Groupies( $MyArray ){
        $Groups = 0;
        for ( $i = 0; $i < count( $MyArray ); $i++ ){
            if( $i == 0 ) {
                if ( $MyArray[$i] == 1 ) $Groups++;
            } else if( $MyArray[$i] == 1 && $MyArray[$i-1] == 0 ) $Groups++;
        }
        return $Groups;
    }

Re: Array Function Needed - Find count of "Groupings"

Posted: Sun Aug 22, 2010 6:47 pm
by HappyJupiter
Wonderful! Works like a charm - thank you!! Just what I needed :)