Jump to content

Small peice of PHP code with big problems


JudgementDay

Recommended Posts

I was wondering if someone can tell me what I have done wrong with this code:

 

<?php
    foreach ($row['received'] as $data) {
        $data += $received;
    }
    echo $received;
?>

It should be adding the number 2 three times, so it should be echoing 6 but its not.

 

Problem 1 I have is that nothing is being added to the variable $received, and problem 2 is that I suspect $received will not become 6, but rather 222. Am I correct?

i dont quite see how the value of $received is being assigned?

 

You are adding it's value to$data and then echoing out $received - but why would that display your new value?

 

try this to test it

 

foreach($row['received'] as &$data) {

$data += $received;
echo $data;
echo "<br/>";
}


print_r($row['received']);

 

Also you need to pass data by reference or it wont change outside of the loop.

I did this:

 

<?php
$received = 0;
while ($row = mysql_fetch_assoc($result)) {
	foreach ($row as $data) {
		$received = $data['received'] + $received;
	}
}
echo $received;
?>

 

I now have two rows of "received", which are '15' and '1'. So, with the above code I was expecting to get 16... but guess what I got?! 7!... I don't know why this happened!

It didn't work, but this did:

 

<?php
$received = 0;
$query = "SELECT * FROM finances";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
	$received = $row['received'] + $received;
}
echo "Received: $".$received." AUD";
?>

 

Much thanks to you, I solved it.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.