php-从逗号分隔的值范围中获取最小值和最大值

时间:2018-12-21 11:46:12

标签: php

我的简单值范围为

0-50000,100000-250000,250000-500000,1000000,

这可能只是0-50000或0-50000,100000-250000,或0-50000,250000-500000或1000000, 如果是1000000,则获得最大值无限

在上述任何一种情况下,我都希望获得最小值和最大值。

如何执行此操作?

1 个答案:

答案 0 :(得分:0)

使用Explode()这个简单的解决方案

$val = '0-50000,100000-250000,250000-500000,1000000';
$min = '';
$max = '';

$valExlode=explode(",",$val);

foreach ( $valExlode as $singleVal ) {
   $singleValExplode = explode ("-",$singleVal);
   foreach ( $singleValExplode as $singleUnit ) {
      if ( $min == '' ) {
        $min = (int)$singleUnit;
      }
      if ( $max == '' ) {
        $max = (int)$singleUnit;
      }
      if ( $singleUnit <= $min ) {
        $min = (int)$singleUnit;
      }
      if ( $singleUnit >= $max ) {
        $max = (int)$singleUnit;
      }
  }
}
echo "Minimum: ".$min;
echo "Maximum: ".$max;

如#Barmar建议