chaking Posted January 12, 2010 Share Posted January 12, 2010 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... Quote Link to comment https://forums.phpfreaks.com/topic/188136-finding-2-consecutive-values-in-array/ Share on other sites More sharing options...
knsito Posted January 12, 2010 Share Posted January 12, 2010 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. Quote Link to comment https://forums.phpfreaks.com/topic/188136-finding-2-consecutive-values-in-array/#findComment-993282 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.