Here is my array how can i find the minimum and maximum value. ie,
output must be min=0;max=15
Array
(
[0] => 5-10
[1] => 10-15
[2] => 0-2
[3] => 15
)
<?php
$price_range=array("0-2","2-5","5-10","10-15","15");
foreach($price_range as $key=>$value){
$a=explode('-',$value);
if($a[0] != ''){$b[]= $a[0];}
if($a[1] != ''){$b[]= $a[1];}
}
echo 'min: '.$min=min($b);
echo 'max: '.$max=max($b);
?>
对数组使用 PHP max()
和min()
函数,假设它在将值设置到数组中之前已经评估了这些值。
遍历数组并检查索引或使用 php 中的 min()/max() 函数
Looks like a prime candidate for using array_reduce()
$price_range = ["0-2","2-5","5-10","10-15","15"];
$min = array_reduce(
$price_range,
function ($carry, $value) {
return min(array_merge(explode('-',$value), [$carry]));
},
PHP_INT_MAX
);
$max = array_reduce(
$price_range,
function ($carry, $value) {
return max(array_merge(explode('-',$value), [$carry]));
},
-PHP_INT_MAX
);
echo 'min: '.$min, PHP_EOL;
echo 'max: '.$max, PHP_EOL;
Try This...
$price=array();
$price_range=array("0-2","2-5","5-10","10-15","15");
foreach($price_range as $key=>$value){
$a=explode('-',$value);
array_push($price,$a[0]);
}
echo 'min: '.$min=min($price);
echo 'max: '.$max=max($price);
$input_range = ['0-2','2-5','5-10','10-15','15'];
$collect = [];
foreach($input_range as $range)
{
$collect = array_merge($collect, explode('-', $range));
}
$min = min($collect);
$max = max($collect);
You can simply make an use of array_walk
along with the min
and max
function as
$price_range = array("0-2","2-5","5-10","10-15","15");
$result = array();
array_walk($price_range,function($v,$k)use(&$result){
$result = array_merge($result,explode('-', $v));
});
echo "Min value = ".min($result)." & Max value = ".max($result);
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.