Damon
Damon

Reputation: 4484

Why is my variable data getting dropped after the first foreach loop?

I am using CodeIgniter to insert records in my database. Everything is working perfectly, except I can't seem to understand why the value of a nested array is losing its value after the first foreach loop.

php

// $data is all data (array) passed from controller method.
public function create($data)
{
    $my_data = array(
        'name' => $data['name'],
        ....
    );

    if ($this->db->insert('myTable', $my_data)) {
        $insert_id = $this->db->insert_id();

        // $data['mySecondCheckbox'] has value here

        foreach ($first_data['myFirstCheckbox'] as $cb1) {
            $first_data = array(
                'fk_foo_id' => $insert_id,
                'fk_cb_id' => $cb1
            );

            $this->db->insert('mySecondTable', $first_data);
        }

        // $data['mySecondCheckbox'] has no value here

         foreach ($data['mySecondCheckbox'] as $cb2) {
            $second_data = array(
                'fk_foo_id' => $insert_id,
                'fk_cb_id' => $cb2
            );

            $this->db->insert('myThirdTable', $second_data);
        }

        return $insert_id;
    } else {
        return false;
    }

}

SOLUTION

Thank you @John! Pretty obvious after sleeping on it. At the time, I was thinking that $data was specific to within each of the each scope.

php

// $data is all data (array) passed from controller method.
public function create($data)
{
    $my_data = array(
        'name' => $data['name'],
        ....
    );

    if ($this->db->insert('myTable', $my_data)) {
        $insert_id = $this->db->insert_id();

        // $data['mySecondCheckbox'] has value here

        foreach ($data['myFirstCheckbox'] as $cb1) {
            $first_data = array(
                'fk_foo_id' => $insert_id,
                'fk_cb_id' => $cb1
            );

            $this->db->insert('mySecondTable', $first_data);
        }

        // $data['mySecondCheckbox'] has no value here

         foreach ($second_data['mySecondCheckbox'] as $cb2) {
            $data = array(
                'fk_foo_id' => $insert_id,
                'fk_cb_id' => $cb2
            );

            $this->db->insert('myThirdTable', $second_data);
        }

        return $insert_id;
    } else {
        return false;
    }

}

Upvotes: 1

Views: 213

Answers (1)

John
John

Reputation: 975

The first line in your foreach loop is resetting the subject in your loop "$data". Rename the variable and you should be good

Upvotes: 2

Related Questions