patternphpMinor
Expanding sizes between given values
Viewed 0 times
expandingsizesbetweenvaluesgiven
Problem
This a very simple function to expand the sizes between the given values.
For instance, if the input variable is "S-XL" then the function returns "S, M, L, XL".
Basically I'm not happy with this function. I think it's too complex for its purpose.
For instance, if the input variable is "S-XL" then the function returns "S, M, L, XL".
Basically I'm not happy with this function. I think it's too complex for its purpose.
function sizexpander($sizes) {
$sizearray=Array("XS", "S", "M", "L", "XL", "XXL", "XXXL");
$size1=array_search(strstrb($sizes, "-"), $sizearray);
$size2=array_search(substr(strstr($sizes, "-"),1), $sizearray);
while ($size1 <= $size2) {
$prodsizes.= $sizearray[$size1].", ";
$size1++;
}
return substr($prodsizes, 0, -2);
}
function strstrb($h,$n){
return array_shift(explode($n,$h,2));
}Solution
You can use the function
You can also just use
In addition I would recommend changing the variable names of
If I were to write this function, it'd look something like this:
array_slice to take the subarray which contains the sizes from $size1 to size2. And then use implode to turn this subarray into a comma-separated string. This will simplify your algorithm.You can also just use
explode instead of substr and strstr to split the range string into its parts.In addition I would recommend changing the variable names of
$size1 and $size2. To me the name $size1 suggests that the variable contains the actual size while in fact it contains its index. Something like index_of_size1 or index_from might be more appropriate.If I were to write this function, it'd look something like this:
function sizexpander($size_range) {
$sizearray=Array("XS", "S", "M", "L", "XL", "XXL", "XXXL");
list($size_from, $size_to) = explode("-", $size_range);
$index_from = array_search($size_from, $sizearray);
$index_to = array_search($size_to, $sizearray);
$subsizes = array_slice($sizearray, $index_from, $index_to-$index_from+1);
return implode(", ", $subsizes);
}Code Snippets
function sizexpander($size_range) {
$sizearray=Array("XS", "S", "M", "L", "XL", "XXL", "XXXL");
list($size_from, $size_to) = explode("-", $size_range);
$index_from = array_search($size_from, $sizearray);
$index_to = array_search($size_to, $sizearray);
$subsizes = array_slice($sizearray, $index_from, $index_to-$index_from+1);
return implode(", ", $subsizes);
}Context
StackExchange Code Review Q#1043, answer score: 6
Revisions (0)
No revisions yet.