CopperRabbit
CopperRabbit

Reputation: 674

Valid array gives php Invalid argument supplied for foreach()

I have the following foreach loop that gives me the invalid argument error:

$all_students = $this -> model_accounts -> get_students_on_account($account['account_id']);

        foreach ($all_students as $student)
        {                               
            ...
        }

I tried to debug using print_r to check what the $all_students array looks like and I got this as a result:

Array
(
    [0] => Array
        (
            [id] => 00062
            [student_name] => Reckless
            [student_surname] => Harmse
            [acc_id] => 198
            [dob] => 07-07-1993
            [gender] => Male
            [active] => 1
            [has_pic] => 1
            [avatar] => 106.jpg
            [pic_ver] => 1
            [student_identity_num] => 9307075052084
        )

)

So the array is there and as seen in the print_r details, it is seen as an array.

I have looked at other similar questions and none of them could help.

Thanx in advance

Added: Model function used to get the students

function get_students_on_account($account_id)
{
    $data = '';     
    $this->db->where('acc_id', $account_id);
    $q = $this->db->get('students');

    if ($q->num_rows() > 0)
    {
        foreach ($q->result_array() as $row)
        {
            $row['dob'] = $this -> change_date_format($row['dob']);
            $data[] = $row;
        }
    }

    return $data;
}

Upvotes: 1

Views: 147

Answers (3)

trincot
trincot

Reputation: 350272

In your function get_students_on_account, replace this:

$data = '';     

by this:

$data = array();

This is needed to consistently return an array. You don't want to return a string. When it does, the problem that you described will occur.

Upvotes: 2

Abdulla Nilam
Abdulla Nilam

Reputation: 38584

Try this

In Controller

$all_students = $this->model_accounts->get_students_on_account($account['account_id']);

if($all_students == false){
    echo "Empty result";
}
else{
    foreach ($all_students[0] as $student)
    {                               
        ...
    }
}

In Model

function get_students_on_account($account_id)
{
    $query = $this->db->query("SELECT * FROM students WHERE acc_id = $account_id");
    $result = $query->result_array();
    $count = count($result);

    if (empty($count)) {
        return false;
    }
    else{
        return $result;
    }

}

Upvotes: 0

Ankush Srivastava
Ankush Srivastava

Reputation: 502

Try this

$res = $q->result_array();    
foreach ($res as &$row)
{
    $row['dob'] = $this -> change_date_format($row['dob']);
}
return $res;

Upvotes: 1

Related Questions