Compare array values with variable

1

I need to add values from an array and compare them with a value coming from a variable.

Ex:

array(1000, 1000, 3000, 5000,);

$var = 4000;

In the case you must add 1000 + 3000 in the array, then you will find the 4000. The array positions will be random, the sum can be between 2,3,4, .. values.

Is it possible only with php?

    
asked by anonymous 31.08.2016 / 15:21

1 answer

4

I think this might help you. I found it here in the Stack Overflow .

   $values  = array(1000, 1000, 3000, 5000);
   $expected = 4000;

   $len = count( $values );
   for( $i = 1; $i < pow( 2, $len ); $i++ ) {
      $soma = 0;
      $set = array();
      for( $j = 0; $j < $len; $j++ ) {
         if( 1 << $j & $i ) {
            $set[] = $j;
            $soma += $values[$j];
         }
      }
      if( $soma == $expected ) {
         // Estamos exibindo na tela apenas como demonstração.
         foreach( $set as $pos ) echo "[$pos]{$values[$pos]} ";
         echo " = $expected<br>\n";
      }
   }
    
01.09.2016 / 20:05