PHP - cannot use a scalar as an array warning

zozo picture zozo · May 16, 2011 · Viewed 139.9k times · Source

I have the following code:

 $final = array();
    foreach ($words as $word) {
        $query = "SELECT Something";
        $result = $this->_db->fetchAll($query, "%".$word."%");
        foreach ($result as $row)
        {
            $id = $row['page_id'];
            if (!empty($final[$id][0]))
            {
                $final[$id][0] = $final[$id][0]+3;
            }
            else
            {
                $final[$id][0] = 3;
                $final[$id]['link'] = "/".$row['permalink'];
                $final[$id]['title'] = $row['title'];
            }
        } 
    }

The code SEEMS to work fine, but I get this warning:

Warning: Cannot use a scalar value as an array in line X, Y, Z (the line with: $final[$id][0] = 3, and the next 2).

Can anyone tell me how to fix this?

Answer

brian_d picture brian_d · May 16, 2011

You need to set$final[$id] to an array before adding elements to it. Intiialize it with either

$final[$id] = array();
$final[$id][0] = 3;
$final[$id]['link'] = "/".$row['permalink'];
$final[$id]['title'] = $row['title'];

or

$final[$id] = array(0 => 3);
$final[$id]['link'] = "/".$row['permalink'];
$final[$id]['title'] = $row['title'];