1

My php script is getting data from an xml file. I am fetching a list of prices and echoing them in a foreach statement. The problem is I need to calculate the sum of prices outside the foreach. Here is what I've done so far. Converting to array then going array_sum is the only thing I can think of.

<?php

$data = simplexml_load_file("products.xml");

foreach ($data as $val) {

echo $val->price . "<br>";

$total[] = $val->price;

}

$sum = array_sum($total);

echo $sum;

So far, this is not returning the total. It simply returns 0, which is weird because when I vardump $total, it shows up as an array.

3
  • Try casting $val->price; to an int. Commented May 9, 2021 at 14:28
  • it shows up as an array. but if it is an empty array, than you will get 0 Commented May 9, 2021 at 14:29
  • Nigel Ren casting the object to int works perfectly. Thanks! Commented May 9, 2021 at 14:37

1 Answer 1

0

When using SimpleXML and you do

$total[] = $val->price;

this creates an array of SimpleXMLElements and not values.

A simple solution in this case is to cast the value, depending on the type of value either

$total[] = (int)$val->price;

or

$total[] = (float)$val->price;
Sign up to request clarification or add additional context in comments.

Comments

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.