Jump to content

Finding 2 consecutive values in array


chaking

Recommended Posts

The array is something like:

 

<?php
$a = array(1,0,1,0,1,0,0,1,1);
?>

 

Is there a way to evaluate the array to see if 2 1's are consecutive? Or if this is easier to read:

 

<?php
$a = array("IN","OUT","IN","OUT","IN","OUT","OUT","IN","IN");
?>

 

I'm trying to execute code anytime 2 INs are consecutive.

 

 

 

This might not be the best way to go about it, but basically I'm trying to determine if something was done before it's other required action has been completed.  So I query the dB and select all of its events in order of the time of the event, and then output it into an array so that I can tell if the proper conditions were met.  If there were 2 INs before an OUT, then that's a problem and needs to be echoed out...

Link to comment
Share on other sites

Basically all you need to do is just keep track of the '1's, if any '0's are met, reset the 1-counter

Below will look for onsecutive 1's

 

$a = array(1,0,1,0,1,0,0,1,1);
$error = false;
$found = 0; //keep track with counter
$count = count($a);
for($i=0;$i<$count;$i++){
    if($a[$i] === 1){ 
        $found++;
    }else{
        $found = 0;
    }
    if($found == 2){
        $error = true;
        break;
    }
}
if($error){
    echo 'Duplicate "1" found at:'. $i; 
}

 

You could also treat the array as a stack using array_pop() / array_shift() functions

 

If you are looking for any consecutive values then just compare the previous and current array values.

 

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.