Giving text labels to integer ranges in PHP
Question by xxdrivenxx
I am attempting to take simple number ranges (in the example of this project, I am working with different increments of money for each user. FAKE money, by the way…) and group them into classes that can be displayed publicly instead of the absolute number.
Here is a rough sample of code for the long way to write this function as an example:
<?
$money=500001;
if($money > 0 AND $money < 5000) {
$class = 'Poor';
} elseif ($money >= 5000 AND $money < 25000) {
$class = 'Lower Class';
} elseif ($money >= 25000 AND $money < 100000) {
$class = 'Middle Class';
} elseif ($money >= 100000) {
$class = 'Upper Class';
}
echo $class;
exit();
?>
Now, I know this function will work, but it seems like an absolutely awful way in going about writing it, since if more $class’ are added, it becomes far too long.
Now my question is: Is there a shorter way to write this? Possibly using range() and/or an array of values?
Answer by alfasin
I would go for something like this:
function getClass($sal){
$classes = array(5000=>"poor", 25000=>"Lower Class", 100000=>"Middle Class");
foreach ($classes as $key => $value) {
if($sal < $key){
return $value;
}
}
return "Upper Class";
}
$salary = 90000;
$sal_class = getClass($salary);
echo "salary class = $sal_classn";
Output:
sal = Middle Class
Answer by Starx
A bit similar to above answer, but a better one. I will suggest using OO approach.
Class Foo {
protected $class = array(
array("poor", 0, 5000),
array("medium", 5000, 25000)
);
function get_class($amount) {
foreach ($this -> class as $key => $value) {
if($amount > $value[1] && $amount < $value[2]) {
return $value[0];
}
}
return null;
}
function add_class(array $arr) {
$this -> class[] = $arr;
}
}
Usage:
$obj = new Foo();
$obj -> get_class(6000); //Outputs: medium
$obj -> add_class(array("rich", 25000, 50000)); //Add a new class
$obj -> get_class(35000); //Outputs: rich