Counting between elements in an array???

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
james_withers
Forum Newbie
Posts: 6
Joined: Mon Aug 04, 2008 8:03 am

Counting between elements in an array???

Post by james_withers »

Hi,

Could someone tell me the best way to count the number of positions between two array values in an array? I have a large array and two values, I want to find the first value in the array first and then count how many positions in the array until the second is hit. I am sorry if this is a bit elementary ...
I also need to be able to identify the value x number of elements away from another value :oops:

Thanks

James
Darkzaelus
Forum Commoner
Posts: 94
Joined: Tue Sep 09, 2008 7:02 am

Re: Counting between elements in an array???

Post by Darkzaelus »

Code: Select all

 
$space=0;
$foundfirst=false;
$foundsecond=false;
$first='test';
$second='test2';
$array=array('test','test1','test2');
foreach($array as $arr => $value) {
    if(!$foundfirst) {
        if($value==$first)
            $foundfirst=true;
    } else {
        if(!$foundsecond) {
            if($value==$second)
                $foundsecond=true;
            $space++;
        }
    }
}
echo $space; //2
}
That should do it! :)

Cheers,

Darkzaelus.
james_withers
Forum Newbie
Posts: 6
Joined: Mon Aug 04, 2008 8:03 am

Re: Counting between elements in an array???

Post by james_withers »

Thanks Darkzaelus
Darkzaelus
Forum Commoner
Posts: 94
Joined: Tue Sep 09, 2008 7:02 am

Re: Counting between elements in an array???

Post by Darkzaelus »

No problem :)
Post Reply