我建议您将数字转换为浮点数,然后再将它们与0 进行比较;这将强制非数字为0,然后您可以一步过滤掉负数、原始零和转换后的零。如果没有符合条件的价格,请提前退货。如果存在至少一个符合条件的价格,则返回两者中较低的一个。
为了方便、简化、DRY 编程,我将值批处理到一个数组中以便快速处理。
代码:(Demo)
function newGetMinPrice($nums) {
$nums = array_filter($nums, function($v){ return (float)$v > 0;}); // convert to float and check if greater than 0
if (empty($nums)) {
return 'error'; // if no qualifying prices, return error
}
return min($nums); // return the lowest qualifying price
}
$tests = [[0, .1], [1, 'foo'], [.24, -.25], [3, 3], ['foo', 'bar'], [-0, 0.1], [90, -90], [0, 0], [1, 1]];
foreach ($tests as $test) {
echo "new: {$test[0]} -vs- {$test[1]} = ",newGetMinPrice($test), "\n";
}
输出:(与您发布的 sn-p 相同的性能
new: 0 -vs- 0.1 = 0.1
new: 1 -vs- foo = 1
new: 0.24 -vs- -0.25 = 0.24
new: 3 -vs- 3 = 3
new: foo -vs- bar = error
new: 0 -vs- 0.1 = 0.1
new: 90 -vs- -90 = 90
new: 0 -vs- 0 = error
new: 1 -vs- 1 = 1
...或者你可以像这样浓缩:
$nums = array_filter($nums, function($v){ return (float)$v > 0;}); // convert to float and check if greater than 0
return empty($nums) ? 'error' : min($nums);
附言如果您不想使用array_filter(),您也可以生成一系列条件...尽管我认为它并不比您原来的 sn-p 更漂亮。
$num1 = max(0, (float)$num1);
$num2 = max(0, (float)$num2);
if ($num1 === 0) { // bad num1
if ($num2 === 0) { // bad num2
return 'error'; // send error
}
return $num2; // send good num2
}
// 1 is good...
if ($num2 === 0 || $num1 <= $num2) { // bad num2 or num1 better than num2
return $num1; // send good/better num1
}
return $num2; // both num1 and num2 are good, send num2
或者不声明newGetMinPrice():
$nums = array((float)$num1,(float)$num2); // force input values to float values
$nums = array_filter($nums, function($v){return $v > 0;}); // check if greater than 0
if (empty($nums)) {
die('error');
} else {
$price = min($nums); // declare lowest qualifying price
}
Demo