Compare array values with variable

Asked

Viewed 594 times

1

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

Ex:

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

$var = 4000;

In this case one must add up within the 1000+3000 array, then 4000 will be found. The array positions will be random, the sum can be between 2,3,4,.. values.

Possible only with php?

  • 2

    Can you explain a little better what you need? Show a practical example, with the array, value and expected result.

  • 2

    gave a double meaning because at first glance it seems that is just add everything and compare.. this is quite easy. But it seems to ask you to get the sum that is equal to the value of the variable.. That’s another conversation.. Describe better what you really need.

  • So in this case, I need to find the value of a variable inside the array with several values, then do all the possible sums of that array and check if it equals the variable.

  • 1

    Put an example in the question, at least with what you have so far it seems that you just want to compare the 4000 with the 1000(2x), 3000 and 5000. That part of the sum was not clear.

  • 2

    @William, then something is missing because if you find the value 4 thousand inside the array, obviously after that, the sum of all the others will never equal the 4 thousand. Unless there’s another value to compare or all the others are zero. It’s confusing. If you want to fetch the specific value within the array, it is as rray posted. But after that is confused his explanation of what that sum would be.

  • @Danielomine edited the question

  • 1

    is clearer.. In this case you have to permute the array data and add it up.. This query can give you a clarification on the permutation: http://answall.com/questions/126783/permuta%C3%A7%C3%A3o-de-array But on the sum, you need a specific implementation

Show 2 more comments

1 answer

4


I think this might help you. I found 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";
      }
   }
  • I’ll do some tests, some things I didn’t understand there in the code.

  • Our that interesting, I tried with all the possibilities and it does not miss a combination. Very good. I will try to implement in my banking conciliation system. Thank you. And that’s right. Congratulations brother.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.