How to subtract values in an array (PHP)?

1

First I generate an array of 3 positions with random numbers, then I try to subtract the three values from the array. The problem is that if the first subtraction gives me a negative number the next value does not subtract it well. For example: $ given = [6,4,4] The subtraction would be: 6-4-4 = -2
But when I execute it, subtraction gives me: 6

My code:

for($i=0;$i<=2;$i++){

             $dado[]=rand(1,6);
             echo $dado[$i].' | ';
        }
$resta=0;

    for($i=0;$i<=2;$i++){
             if($dado[$i]>=0){
             $resta=$dado[$i]-$resta;
             }elseif($dado[$i]<0){
             $resta=$dado[$i]+$resta;        
             }
        }       
    
asked by SakZepelin 29.11.2018 в 12:44
source

2 answers

1

You had an approach failure. I put your modified code to work and then I will comment:

for($i=0;$i<=2;$i++){
        $dado[]=rand(1,6);
        echo $dado[$i].' | ';
    }

    $resta=$dado[0];

    for($i=1;$i<=2;$i++){
        if($dado[$i]>=0){
            $resta=$resta-$dado[$i];
        }elseif($dado[$i]<0){
            $resta=$dado[$i]+$resta;        
        }
    }

    echo '<br />';
    echo 'La resta es: ' . $resta;

The value of $resta should start with value as the first number of your dice roll, since it is to this number that you want to subtract the next one from. For this reason, the loop for with which you make the subtraction should start from position 1 instead of 0.

You also had the wrong operation in which you calculated the subtraction and assigned it to $resta . The die is the one that must be subtracted from the value of $resta and not the other way around. Remember that the order of the operands in the case of subtraction if that affects the result.

    
answered by 29.11.2018 в 13:01
0

This check is:

 $dado[$i] >= 0 

The random value is between 1 and 6, therefore it will always be greater than 0.

It is badly raised. I add the correct approach and comments so you can see what each line does.

for($i=0;$i<=2;$i++){
    $dado[]=rand(1,6); // Ejemplo de valores obtenidos [6,4,4]
    echo $dado[$i].' | ';
}

$resta=$dado[0]; // Obtener el primer numero (6)

for($i=1;$i<=2;$i++){ //recorrer el array empezando por los valores que se van a restar; [4,4]
    $resta -= $dado[$i]; // restar los valores -4 y -4
}

echo '<br />';
echo 'La resta es: ' . $resta; //resultado -2
    
answered by 29.11.2018 в 14:06