Find first gap in array?!?

I’m trying to figure out how to find the first gap in a row of numbers in an array.

I have a bunch of “tiles” which anatomy looks like this:
1,g,45,3

The first number is the “tiles” position in the row. There can be max 28 positions. I get the tiles in the row like this:
1,g,17,85,2,g,28,97,3,k,11,89,6,e,5,77

One long string which I break up and then get the positions from like this:

$playertiles = '1,g,17,85,2,g,28,97,3,k,11,89,6,e,5,77';

$playertilesarray = explode(",",$playertiles);
$h = '';
$k = 0;
foreach($playertilesarray as $value){
	$h .= ($k%4 == 3)?$value.';':$value.',';
	$k++;
}
$playertilesarray = explode(";",substr($h,0,-1));

echo 'Playertiles';
echo '<pre>';
print_r($playertilesarray);
echo '</pre>';

foreach($playertilesarray as $test){
	$printArray = explode(",", $test);
	$position = $printArray[0];
	$theposition[] = $position;
}

echo 'Tilepositions';
echo '<pre>';
print_r($theposition);
echo '</pre>';

Now the $theposition array comes out like this:

Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 6
)

As you can see I want to be able to get number 4 in an variable for later use. It is the first number missing in the row of the 28 number running from 1 - 28.

Hope this make sense and hoping 4 help :slight_smile:

I think I understand your problem.
One approach that comes immediately to mind is this:
Walk the array, applying a math operation (subtraction) to each member against its predecessor.
If the result is greater than one you know you found a gap.

Does that help?

Sounds like an idea, but not sure how to approach… Arrays are not my strongest side…

I really don’t understand what you’re saying.

And given that preface…



$start = array_shift($playertilesarray);

foreach($playertilesarray as $v){ 
    if ($start + 1 != $v) {
        $missing = $start + 1; 
        break;
    }

    $start = $v;
}

# the missing number is: $missing

Works like a charm except of one thing. If there is no number 1 it wont jumps that and gives the next number missing?

So if it goes… 2,3,4. You want $missing = 1?

Correct

Change

$start = array_shift($playertilesarray);

to

$start = 0;