title: php - How to count array values and keys until a target is reached
body: <p>I have an array of values and I need to count them but only until I reach the $target amount. I need to know how many array keys are required to reach the target ($count) and the sum total of those corresponding values ($total). Here's the array I'm using:</p>
  
  <pre><code>$numbers = Array ( [0] =&gt; 1 [1] =&gt; 1 [2] =&gt; 1 [3] =&gt; 1 [4] =&gt; 6 [5] =&gt; 1 [6] =&gt; 5.5 [7] =&gt; 1 [8] =&gt; 1 [9] =&gt; 1 [10] =&gt; 1 [11] =&gt; 1 [12] =&gt; 1 [13] =&gt; 11 )
  </code></pre>
  
  <p>With the <code>$target=9</code> the <code>$total</code> should be 10 and the $count should be 5 but I'm getting <code>$total=9</code> and <code>$count=9</code> as the code appears to be counting the keys rather than values. Similarly if the target were 12 then <code>$total</code> should be 16.5 and the <code>$count</code> should be 7 but i get 12 and 12.</p>
  
  <p>Hope it all makes sense. If someone can edit this code so that it works for any array of numbers and any target it would be greatly appreciated.</p>
  
  <pre><code>$count=0;
  $target=9;
  $total=0;
  foreach($numbers as $key =&gt; $value){
  while($total &lt; $target) {
  $total = $total+$value;
  $count++;
  }
  }
  echo "total is $total and count is $count";
  </code></pre>