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?

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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!

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.