0

I am trying to plus all array values like :

$arr = array('55','55','99'); // I want to do 55 + 55 + 99 = X

My function:

function get_value_of_vouchers($id){
  global $db;
  $prices = array();
  $query = $db->query("SELECT * FROM vouchers WHERE uid='$id' ORDER BY id");
  if ($query->num_rows > 0) {
    while ($row = $query->fetch_assoc()) {
      $fixed_prices = get_price_by_id($row['price']); 
      // returned e.g : 250 | 500 | 1500
      array_push($prices, $fixed_prices);  

      //var_dump($prices); - Printed - array(1) { [0]=> string(4) "5000" } array(2) { [0]=> string(4) "5000" [1]=> string(3) "250" } array(3) { [0]=> string(4) "5000" [1]=> string(3) "250" [2]=> string(3) "250" }
      return array_sum($prices);
    }
  }
}

Always when I am trying to do array_sum I am getting a wrong number.

raina77ow
  • 103,633
  • 15
  • 192
  • 229
Dani Prime
  • 59
  • 7
  • 3
    `return array_sum($prices);` statement should be outside of `while` loop. – raina77ow Jan 09 '18 at 21:16
  • Your array is 2d. So instead of `rray_sum($prices)` write `rray_sum(array_column($prices, index_you_want_to_sum))` – splash58 Jan 09 '18 at 21:41
  • @raina77ow Your comment is not seeking clarification or question improvement. Please do not add solutions as comments. https://meta.stackexchange.com/questions/230676/hey-you-yeah-you-post-your-answers-as-answers-not-comments/296481#296481 – mickmackusa Jan 09 '18 at 21:49
  • @splash58 Your comment is not seeking clarification or question improvement. Please do not add solutions as comments. https://meta.stackexchange.com/questions/230676/hey-you-yeah-you-post-your-answers-as-answers-not-comments/296481#296481 – mickmackusa Jan 09 '18 at 21:49
  • get_price_by_id takes a price as a parameter and not an id? also it sounds like it should return a single value and not an array. Can you explain what get_price_by_id is supposed to do? – dhinchliff Jan 10 '18 at 10:22

1 Answers1

2

Why dont you simply do it from sql query like below

$query = $db->query("SELECT SUM(price) as total_price FROM vouchers WHERE uid='$id' ORDER BY id");

Better use prepared statement like below

 $stmt=$mysqli->prepare("SELECT SUM(price) as total_price FROM vouchers WHERE uid=? ORDER BY id");
 $stmt->bind_param("i", $id);
 $stmt->execute();
 $stmt->bind_result($total);
 $stmt->fetch();
 echo $total;
sumit
  • 15,003
  • 12
  • 69
  • 110