Lets say I have an array full of years.
array(
'1991',
'1992',
'1993',
'1994',
'1995',
'1999',
'2000',
'2001'
)
How can I display that array as β1991-1995, 1999-2001β
Thanks guys
Lets say I have an array full of years.
array(
'1991',
'1992',
'1993',
'1994',
'1995',
'1999',
'2000',
'2001'
)
How can I display that array as β1991-1995, 1999-2001β
Thanks guys
you mean βhow do i find gaps in my arrayβ?
Semi-sloppy way:
$curval = array[0];
foreach($array AS $year) {
if($year != $curval + 1) {
echo "-".$curval.", ".$year;
}
$curval = $year;
}
echo "-".$curval;
Note: Will look odd if the first value or last value in the array are a gap year (1995,2000,2001,2004 will be presented as: 1995-1995,2000-2001,2004-2004)
How about array_chunk?
$array = array(
'1991',
'1992',
'1993',
'1994',
'1995',
'1999',
'2000',
'2001'
);
print_r(array_chunk($array, 5, true));
Would only work if the chunks are always the same size.
Yes, agreed!
There might be an easier way to do this, but this is how I got it done.
// Set needed variables
$years = array('1991', '1992', '1993', '1994', '1999', '2000', '2001', '2002');
$index = 0;
$delimitter = '';
foreach($years as $year) {
// Get last index
if($index != 0) {
$last_index = $index - 1;
}
// Get next index
$next_index = $index + 1;
if($index == 0) {
echo $year->name;
} elseif ($year->name - 1 == $years[$last_index]->name) {
if($delimitter != '-') {
$delimitter = '-';
echo $delimitter;
}
if(isset($years[$next_index])) {
if($years[$next_index]->name != $year->name + 1) {
echo $year->name;
}
} else {
echo $year->name;
}
} else {
$delimitter = ', ';
echo $delimitter . $year->name;
}
$index++;
}
Cheers
Hereβs a similar question from last year: http://www.sitepoint.com/forums/showthread.php?665995-how-to-add-commas-and-dashes-for-numbers-ie-1-10-or-1-4-13