65

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?

1

4 Answers 4

106

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'];
3
  • 1
    You can simplify some lines in the first case to $final[$id][] = 3; and in the second to $final[$id] = array(3); :)
    – Tadeck
    Commented May 16, 2011 at 16:07
  • 2
    @Tadeck yes you can, I thought I would be explicit though ; )
    – brian_d
    Commented May 16, 2011 at 16:46
  • 8
    This solution solved my problem, but the "why" of it eludes me. PHP, as far as I've ever used it, doesn't require you to declare a variable's type. My code was working fine, and then it last night started spewing this error for some inexplicable reason, out of the clear blue sky. As a matter of course, in my MVC (CodeIgniter) code I routinely assign the $data = array() type at the top of my functions. In my plain jane php, I rarely do. In php, I don't think it's mandatory. Yet, declaring my variable as an array type solved my problem. Perplexed.
    – TARKUS
    Commented Jul 5, 2016 at 10:56
97

The reason is because somewhere you have first declared your variable with a normal integer or string and then later you are trying to turn it into an array.

0
3

The Other Issue I have seen on this is when nesting arrays this tends to throw the warning, consider the following:

$data = [
"rs" => null
]

this above will work absolutely fine when used like:

$data["rs"] =  5;

But the below will throw a warning ::

$data = [
    "rs" => [
       "rs1" => null;
       ]
    ]
..

$data[rs][rs1] = 2; // this will throw the warning unless assigned to an array
1
  • 2
    I think in this case it's because you forgot to quote the rs and rs1 on the last line. That makes them undefined constants, and so $data[rs] is not defined.
    – Doin
    Commented Mar 20, 2022 at 13:22
-1

Also make sure that you don't declare it an array and then try to assign something else to the array like a string, float, integer. I had that problem. If you do some echos of output I was seeing what I wanted the first time, but not after another pass of the same code.

Not the answer you're looking for? Browse other questions tagged or ask your own question.