6

As mentioned on http://php.net/manual/en/language.types.array.php

Note: As of PHP 7.1.0, applying the empty index operator on a string throws a fatal error. Formerly, the string was silently converted to an array.

Can someone please tell me what does that mean with an example?

How will it affect my code?

Thanks!

2 Answers 2

7

In PHP < 7.1:

$var = 'somestring';
$var[] = 'a'; # yields array with two elements ['somestring', 'a']

In PHP >= 7.1 this yields

Fatal error: Uncaught Error: [] operator not supported for strings

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

5 Comments

This sounds right. But I'm seeing that error affect 5.6 and 7.0 as well...?
Is there any alternative solutions to this? I have some code where I am using this and I can't change the variable name.
@DevAggarwal: What is your exact problem?
@JiriHrazdil Hey, Thanks for the help. I am using php 7.0 for now. And this works perfectly fine with it. I'll try php 7.1 later. :)
@JiriHrazdil : It's throwing fatal error with PHP 5.6.30 just like with PHP 7.1.0, rather than silently converting the string to an array which is supposed to happen if the text from PHP manual is to be believed. It's not happening like the code you mentioned in your answer with PHP 5.6.30
0

The wording in the docs is a bit weird but what changed in 7.1 is when you have an empty string and then access it that way: 3v4l.org/V5YJa

Have a look at below code :

<?php
$rootbeer = '';
$rootbeer[] = 'T';
?>

Output with PHP 7.1.0 :

Fatal error: Uncaught Error: [] operator not supported for strings in your_file.php:4
Stack trace:
#0 {main}
  thrown in your_file.php on line 4

With PHP versions prior to PHP 7.0.1, the string gets silently converted to an array without issuing any warning or error.

I hope this would have cleared your doubt.

1 Comment

I'd say the wording in the docs slides towards being factually incorrect and not just weird.

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.