Jump to content

[SOLVED] Check if array contains consecutive numbers


Thomisback

Recommended Posts

Hi,

I'm having a really interesting problem, after searching for some time I decided to post it here.

For example if I have an array like this:

 

//Creates an array with elements.
$theVariable = array("1", "5", "8", "15", "16", "17", "23", "44", "45");

 

How would I change it so there are no more consecutive numbers?

Like this:

 

//Creates an array with elements.
$theVariable = array("1", "5", "8", "16", "23", "44");

 

Suggestions are welcome...

Kind regards

Link to comment
Share on other sites

try that, and I just gave a lecture about giving out scripts :'( I'm a hypocrite

 

but this was fun :D

 

<?php
$array = array(1,3,4,7,8,12,13,14);
foreach ($array as $k => $v) {
	if (isset($prev)) {
		if (($v - $prev) != 1) $newArray[] = $v;
	} else { $newArray[] = $v; }
	$prev = $v;
}
print_r($newArray);
?>

Link to comment
Share on other sites

Haha thanks :)

 

I just tried it, the array in your example:

  $array = array(1,3,7,12,13,14); 

 

Should return something like:

 

  $array = array(1,3,4,7,12,14); 

 

But gives me:

Array ( [0] => 1 [1] => 3 [2] => 7 [3] => 12 )

 

Any help? :P

 

Never mind I think it works :P Let me try that again XD

Link to comment
Share on other sites

Just to play the devil's advocate here....

 

What about an array that was like this....

 

$numbers = array(1, 6, 7, 3, 2, 5, 66, 22, 78);

 

Are you already sorting the array somewhere in your code, or does the array get created in a way that there will *never* be larger numbers before smaller numbers or consecutive numbers that are not next to each other in the array?

 

nate

 

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.