1

I am trying to get the total number of bikes available in a bike share system. I am using php and simpleXML to filter the XML data.

I have successfully retrieved the number of bikes at each station.

foreach ($xml->station as $items) {
print $items->nbBikes;
}

But I want the total number of bikes available at all stations. I tried this to declare a variable ($totalBikes) that added to itself each time through the foreach statement, but it did not work.

foreach ($xml->station as $items) {
print $items->nbBikes;

    $numberOfBikes = $items->nbBikes;   
    $totalBikes= $numberOfBikes += $numberOfBikes;

}

 print $totalBikes;

Can anyone please suggest a way to get the total number of bikes?

Thanks!

3 Answers3

1

You want to add $numberofbikes to $totalbikes, not to itself:

$totalBikes += $numberOfBikes;

which is a shortcut version of

$totalBikes = $totalbikes + $numberOfBikes;

Be sure you're declaring '$totalbikes' before your foreach loop though so it doesn't get reset on each iteration.

Toby Allen
  • 10,997
  • 11
  • 73
  • 124
k3davis
  • 985
  • 12
  • 29
0

You declared $totalBikes within the loop, so it is getting reset every time you iterate. Also, you're not adding $numberOfBikes to $totalBikes properly. Try this:

$totalBikes = 0;
foreach ($xml->station as $items) {
    $numberOfBikes = $items->nbBikes;
    $totalBikes += $numberOfBikes;
}
print $totalBikes;
beachwood23
  • 431
  • 2
  • 5
  • 14
0

Instead of iterating, use xpath:

$bikes = $xml->xpath("/stations/station/nbBikes");
$sum = array_sum(array_map("intval", $bikes));

line 1 will select all <nbBikes> into an array, but as SimpleXml objects
line 2 will first transform all elements to Integer, then add them up.

Note: For a one-liner, there's a sum-function in xpath, but I couldn't get it to work. Any ideas why?

$sum = $xml->xpath("sum(/stations/station/nbBikes)")[0];
michi
  • 6,565
  • 4
  • 33
  • 56