2

On older PHP versions I could do the following.

$arr = ['foo', 'bar'];
var_dump($arr);
foreach ($arr as $i => $v) {
    $arr[$i]['string'] = 'baz';
}

Now when I'm doing such an operation in PHP7, it fails with the following error:

Illegal string offset 'string' [sample.php, line 4]

Why is this and why can't I do this anymore? I already found a lot of answers about typecasting in PHP7, that it's not that graceful anymore, so I suspect it has to do with that, but I can't find my answer on the web. Am I missing something?

The var_dump result from line 2

array (size=2)
  0 => string 'boo' (length=3)
  1 => string 'bar' (length=3)

after the foreach I was expecting the following result

array (size=2)
  'foo' => 
    array (size=1)
      'string' => string 'baz' (length=3)
  'bar' => 
    array (size=1)
      'string' => string 'baz' (length=3)
4
  • 3
    Why would you even do $arr[$i]['string'] = 'baz';? Accessing the field string of a string doesn't seem logical at all. Why not $arr[$i] = ['string' => 'baz'];? edit: Looking closer at your expected output, I'm even more perplexed. How do you expect the value of the array to suddenly become keys? Long story short, that's simply not how PHP works. Commented Nov 4, 2016 at 20:51
  • 3
    Is it because neither 'foo' nor 'bar' are arrays so cannot have elements pushed into them? Commented Nov 4, 2016 at 20:53
  • I feel very stupid at this moment. I wasn't accessing the type of array I thought I was. So in m sample I was recreating what happened, but that messed up my thoughts even more. Thinking about what @FelixKling said did the trick to get my mind straight again. Commented Nov 4, 2016 at 20:57
  • Could one of you add an answer. Then I'll mark it as solved. Commented Nov 4, 2016 at 21:01

1 Answer 1

2

$arr[$i]['string'] = 'baz'; is not assigning to what you think it is. To take it step-by-step:

$arr[$i] is an item in $arr. $arr is an array of strings. Let's say $i is 0, then we now have 'foo'.

$arr[$i]['string'], then, is an item in a string, in this case 'foo'. Strings only have numbered character offsets (in this case they would be 0, 1 and 2). 'string' is not an integer, so it is not character offset, and you get an error.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.