69

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

108

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']; 
Sign up to request clarification or add additional context in comments.

3 Comments

You can simplify some lines in the first case to $final[$id][] = 3; and in the second to $final[$id] = array(3); :)
@Tadeck yes you can, I thought I would be explicit though ; )
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.
96

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.

Comments

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 Comment

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.
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.