如何使用php从数组值中减去数字?

时间:2022-01-26 12:21:30

I have this array.

我有这个数组。

$val = array(1, 0, 2, 1, 1);

I want to subtract 3.5 from $val array in the way that from every element that element not become negative like this:

我想从$val数组中减去3。5就像从每个元素中元素不会变成负数一样

$val = array(0, 0, 0, 0.5, 1)

2 个解决方案

#1


3  

Iterate array items and in loop check if target value is great that loop item, subtract item value from target value. If loop item is great than target value, subtract target value from loop item.

迭代数组项并在循环中检查目标值是否大于循环项,从目标值中减去项目值。如果循环项大于目标值,则从循环项中减去目标值。

$val = array(1, 0, 2, 1, 1);
$subtract = 3.5;
foreach ($val as $key => $item){
    if ($subtract >= $item){
        $subtract -= $item; 
        $val[$key] = 0;
    } else {
        $val[$key] -= $subtract;
        $subtract = 0;
    }
}

See result in demo

看到结果演示

#2


1  

One other possible approach: reduce the subtract value by the value of the current iteration, then set the current value to either zero or -$subtract. Break when $subtract drops below zero.

另一种可能的方法是:将当前迭代的值减去减值,然后将当前值设置为0或-$减值。当$减值降至0以下时终止。

foreach ($val as &$number) {
    $subtract -= $number;
    $number = ($subtract > 0) ? 0 : -$subtract;
    if ($subtract <= 0) break;
}

#1


3  

Iterate array items and in loop check if target value is great that loop item, subtract item value from target value. If loop item is great than target value, subtract target value from loop item.

迭代数组项并在循环中检查目标值是否大于循环项,从目标值中减去项目值。如果循环项大于目标值,则从循环项中减去目标值。

$val = array(1, 0, 2, 1, 1);
$subtract = 3.5;
foreach ($val as $key => $item){
    if ($subtract >= $item){
        $subtract -= $item; 
        $val[$key] = 0;
    } else {
        $val[$key] -= $subtract;
        $subtract = 0;
    }
}

See result in demo

看到结果演示

#2


1  

One other possible approach: reduce the subtract value by the value of the current iteration, then set the current value to either zero or -$subtract. Break when $subtract drops below zero.

另一种可能的方法是:将当前迭代的值减去减值,然后将当前值设置为0或-$减值。当$减值降至0以下时终止。

foreach ($val as &$number) {
    $subtract -= $number;
    $number = ($subtract > 0) ? 0 : -$subtract;
    if ($subtract <= 0) break;
}