phparrayswarningsscalar

Fatal error: Uncaught Error: Cannot use a scalar as an array warning


I have the following code:

 $final = [1 => 2];
 $id = 1;

 $final[$id][0] = 3;

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

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

Can anyone tell me how to fix this?


Solution

  • 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'];