Page 1 of 1

Counting between elements in an array???

Posted: Thu Sep 25, 2008 10:22 am
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

Re: Counting between elements in an array???

Posted: Thu Sep 25, 2008 2:04 pm
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.

Re: Counting between elements in an array???

Posted: Fri Sep 26, 2008 3:41 am
by james_withers
Thanks Darkzaelus

Re: Counting between elements in an array???

Posted: Fri Sep 26, 2008 4:11 am
by Darkzaelus
No problem :)