Michael Grigsby
Michael Grigsby

Reputation: 12163

Variables will not hold a value in a foreach loop

I have a very odd problem with the following code. For some reason I can't get $id1 or $id2 to hold values unless it is placed outside the if and else...if statements. The variables simply will not register. Does anybody see what I am doing wrong? I'm at a loss..

public function addCommentToStartpageWall() {
        $userid = $this->session->userdata("userid");
        $postingUserId = $this->input->post("postinguserid");

        $query = $this->db->query("SELECT * FROM churchmembers");
        $row = $query->row();
        foreach ($query->result() as $row) {
            if ($postingUserId == $row->cMuserId) { // check to see what church the posting user is a member of
                $id1 = $row->cMchurchId; // if posting user is a member of a church set it to var id1
            } if ($userid == $row->cMuserId) { // check to see what church myuserid is a member of
                $id2 = $row->cMchurchId; // if myuserid is a member of a church set it to var2
            } if ($id1 == $id2) { // if posting user and myuserid are a member of the same church process the following
                echo json_encode(array('id1' => $id1, 'isMembershipSame' => true));
            } elseif ($id1 != $id2) { // if posting user and myuserid are not a member of the same user process the following
                echo json_encode(array('id1' => $id1, 'isMembershipSame' => false));
            }
        }
    }

Upvotes: 0

Views: 579

Answers (2)

Ben
Ben

Reputation: 905

Looks like i was wrong too, above answer is correct.

I would recommend resetting your $id1 and $id2 variables each loop however, to prevent them from holding values from the previous iteration:

foreach ... 
{
    $id1 = "";
    $id2 = "";

    // ...
}

Upvotes: 1

Valkyrio
Valkyrio

Reputation: 33

You have to declare/initiate those variables outside of the loop. I believe it's matter of scope - once the loop ends, those variables are trashed.

Edit: I was wrong - I'd guess it's that your if/else aren't evaluating properly.

Upvotes: 0

Related Questions