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.

5
  • 3
    return array_sum($prices); statement should be outside of while loop. Commented Jan 9, 2018 at 21:16
  • Your array is 2d. So instead of rray_sum($prices) write rray_sum(array_column($prices, index_you_want_to_sum)) Commented Jan 9, 2018 at 21:41
  • @raina77ow Your comment is not seeking clarification or question improvement. Please do not add solutions as comments. meta.stackexchange.com/questions/230676/… Commented Jan 9, 2018 at 21:49
  • @splash58 Your comment is not seeking clarification or question improvement. Please do not add solutions as comments. meta.stackexchange.com/questions/230676/… Commented Jan 9, 2018 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? Commented Jan 10, 2018 at 10:22

1 Answer 1

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;
Sign up to request clarification or add additional context in comments.

1 Comment

May be it's not that direct, and some calculations should be applied to the given price.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.