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

大兔子大兔子 提交于 2019-12-12 02:53:45

问题


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 +';
}

回答1:


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;



回答2:


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);



回答3:


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. (breaking 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;
  }
}



回答4:


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


来源:https://stackoverflow.com/questions/9242541/php-echo-a-number-using-else-if-and-greater-than-or-less-than

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!