Dev Aggarwal
Dev Aggarwal

Reputation: 783

Php 7.1 - Empty index operator array

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!

Upvotes: 6

Views: 2391

Answers (2)

user9059272
user9059272

Reputation:

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.

Upvotes: 0

Jirka Hrazdil
Jirka Hrazdil

Reputation: 4021

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

Upvotes: 7

Related Questions