I have a catalogue of activities that are marked based on the age group that they are relevant to. There are 14 checkboxes for checking what grades. K, 1 - 12, and Adult. I have a switch statement to change the K and Adult to a numeric representation.
The following PHP code grabs the grades checked and displays them in consecutive groups. Aka. K, 1, 2, 3, 5, 6, 7, 10, 11, Adult will display as K - 3, 5 - 7, 10 - Adult.
What I would like to ask is, is this a clumsy solution for my problem? Can I learn to make this more efficient or less prone to issues?
Thanks!
// generated through database, but set manually here for testing
$new_grades_array = array(K, 1, 2, 3, 5, 6, 7, 10, 11, Adult)
// grades related variables
$last = ""; // records previous grade in loop for checking consecutiveness
$display = ""; // concatenated display of results
$conseq = FALSE; // records if previous grade was consecutive
for ($i = 0; $i < count($new_grades_array); $i++):
// set grade digit for K and Adult
switch ($new_grades_array[$i]):
case "K":
$currentgrade_dig = 0;
break;
case "Adult":
$currentgrade_dig = 13;
break;
default:
$currentgrade_dig = $new_grades_array[$i];
endswitch;
// concatenates string to display variable based on situation
if ($i == 0): // if the first grade listed
$display = $new_grades_array[$i];
elseif ($i +1 == count($new_grades_array)): //if the last grade listed
if ($conseq != FALSE):
$display .= " - " . $last . ", " . $new_grades_array[$i];
else:
$display .= ", " . $new_grades_array[$i];
endif;
$conseq = FALSE;
elseif ($currentgrade_dig - $last ==1): // if consecutive number from previous
$conseq = TRUE;
else: // if not a consecutive number
if ($conseq != FALSE):
$display .= " - " . $last . ", " . $new_grades_array[$i];
$conseq = FALSE;
else:
$display .= ", " . $new_grades_array[$i];
endif;
endif;
$last = $new_grades_array[$i];
endfor;
print $display;