简体   繁体   中英

PHP Echo a number using else if and greater than or less than

I have a script which is like a whois database. This function returns site views and I want to echo between value.

How can I echo and return one result? If the number is say 4000, it should return only 1k-10k

Rows are like

1550330

1000000

The code:

$siteTotalViews=1000000;
if($siteTotalViews <= 100){
    echo '0-100';
}
if($siteTotalViews <= 1000){
    echo '100-1k';
}
if($siteTotalViews <= 10000){
    echo '1k-10k';
}
if($siteTotalViews <= 100000){
    echo '10k-100k';
}
if($siteTotalViews <= 1000000){
    echo '100k-1 mil';
}
if($siteTotalViews <= 2000000){
    echo '1 mil-2 mil';
}
if($siteTotalViews <= 5000000){
    echo '2 mil-5 mil';
}
if($siteTotalViews <= 10000000){
    echo '5 mil-10 mil';
}
if($siteTotalViews >= 10000000){
    echo '10 mil +';
}

Quick fix:

$siteTotalViews=1000000;
if($siteTotalViews <= 100){
    echo '0-100';
}
//next else is new
else if($siteTotalViews <= 1000){
    echo '100-1k';
}
//next else is new
else if($siteTotalViews <= 10000){
    echo '1k-10k';
}
//next else is new
else if($siteTotalViews <= 100000){
    echo '10k-100k';
}

Better fix:

$names=array(
  100 => '0-100',
  1000 => '100-1k',
  10000 => '1k-10k',
  ...
}

foreach ($names as $count=>$name)
  if ($siteTotalViews<$count) break;

echo $name;

You could create a function that return the interval. When the function hit the return statement it stops executing, so you will only get one value back. Then you can call the function and echo the result:

function getInterval($siteTotalViews) {

  if($siteTotalViews <= 100){
      return '0-100';
  }
  if($siteTotalViews <= 1000){
      return '100-1k';
  }

  ...

}

echo getInterval(1000);

You could put all the limits and their corresponding text into an array and then loop over the reverse array to find the appropriate output. ( break ing the loop when a limit has been hit)

$siteTotalViews=1000000;
$outputs = array(
  0 => '0-100',
  100 => '100-1k',
  1000 => '1k-10k',
  10000 => '10k-100k',
  100000 => '100k-1 mil',
  1000000 => '1 mil-2 mil',
  2000000 => '2 mil-5 mil',
  5000000 => '5 mil-10 mil',
  10000000 => '10 mil +' );
$outputs = array_reverse($outputs);

foreach ($outputs as $limit => $text) {
  if ($siteTotalViews >= $limit) {
    echo $text;
    break;
  }
}
$siteTotalViews=1000000;
 if($siteTotalViews >= 0 && $siteTotalViews <=100 ){    
echo '0-100'; } 
if($siteTotalViews >=101 && $siteTotalViews <= 1000){    
 echo '100-1k'; } 
.....
   if($siteTotalViews >= 10000000){     
echo '10 mil +'; } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM