Jump to content

[SOLVED] Creating a list of numbers (143-160, 172-181 etc)


redbrad0

Recommended Posts

I have a list of ID's that I would like to compile a easy to read list of ID's. Instead of listing out the numbers like

143,144,145,146,147,148,.....

I would like a easy to read list of the ID's grouped together like below. Does anyone have any suggestions?

143-160, 172-181

try

<?php
$nums = '1,2,3,4,6,7,8,10,12,13,14,16';
$na = explode (',', $nums);
$k = count ($na);

$grp_start = $na[0];
echo $na[0];                           
for ($i=1; $i<$k; $i++)
{
    if ($na[$i] - $na[$i-1] > 1)
    {
        if ($na[$i-1]==$grp_start)
            echo ', ';
        else 
            echo '-', $na[$i-1], ', ';
        echo $na[$i];
        $grp_start = $na[$i];
    }
}
if ($na[$i-1] != $grp_start) echo '-', $na[$i-1];  // edit: finish of last group if needed

?>

--> 1-4, 6-8, 10, 12-14, 16 

Thanks for the information. I used it to create the following function which needs a array passed to it. This way it will make sure the numbers are in the correct order.

 

function DisplayFriendlyNumbers($NumbersArray)
{
	$final = "";
	if(is_array($NumbersArray))
	{
		sort($NumbersArray);

  		// Pack the Ticket #'s into a list
  		$Numbers = "";
  		foreach ($NumbersArray as $id)
  			$Numbers .= $id . ", ";
  		$Numbers = rtrim($Numbers, ", ");
  		
		$na = explode (',', $Numbers);
		$k = count ($na);

		$grp_start = $na[0];
		$final .= $na[0];                           
		for ($i=1; $i<$k; $i++)
		{
			if ($na[$i] - $na[$i-1] > 1)
			{
			  if ($na[$i-1]==$grp_start)
			      $final .= ', ';
			  else 
			     $final .= '-' . trim($na[$i-1]) . ', ';
			  $final .= trim($na[$i]);
			  $grp_start = $na[$i];
			}
		}
		if ($na[$i-1] != $grp_start)
			$final .= '-' . trim($na[$i-1]);  // edit: finish of last group if needed
	}
	return $final;
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.