Array Function Needed - Find count of "Groupings"

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
HappyJupiter
Forum Newbie
Posts: 6
Joined: Sat Aug 14, 2010 10:36 am

Array Function Needed - Find count of "Groupings"

Post 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!
User avatar
MindOverBody
Forum Commoner
Posts: 96
Joined: Fri Aug 06, 2010 9:01 pm
Location: Osijek, Croatia

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

Post 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;
    }
HappyJupiter
Forum Newbie
Posts: 6
Joined: Sat Aug 14, 2010 10:36 am

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

Post by HappyJupiter »

Wonderful! Works like a charm - thank you!! Just what I needed :)
Post Reply