PHP simplify range creation
556
I wrote this code to generate range of numbers.
Can someone help me simplify this code. I assume that it can be done in much more simpler and cleaner way, but don't know how ?
$variant_ids = 'AB0000001, AB0000002, AB0000003 - AB0000010, AB0000011 - AB0000020, AB0000021, AB0000022';
$delimiter = ',';
$range_delimiter = '-';
$variant_ids = array_filter(array_map('trim', explode($delimiter, $variant_ids)), 'strlen');
if (is_array($variant_ids)) {
foreach ($variant_ids as &$variant_id) {
if (strpos($variant_id, $range_delimiter) !== FALSE && substr_count($variant_id, $range_delimiter) == 1) {
$variant_range_id = array_map('trim', explode($range_delimiter, $variant_id));
$variant_id = array();
for ($i = $variant_range_id[0]; $i <= $variant_range_id[1]; $i++) {
$variant_id[] = $i;
}
$variant_id = implode($delimiter, $variant_id);
}
}
}
$variant_ids = implode($delimiter, $variant_ids);
echo '<pre>'; print_r($variant_ids); echo '</pre>';
Answer
Solution:
Interesting concept that I believe that PHP’s built in
function can handle well. Reworked your logic to work with the concept as arrays using
,
& some regex juggling. Not perfect, but based on your original code’s needs it seems to be a nice alternative if I do say so myself.