Declaring a variable as a string and later using it as an array?

210 views Asked by At

Did something change in the PHP where declaring a variable as a string and later using it as an array is not OK. We upgraded to bitnamies wamp stack and it broke our app. One of the variables

$change="";

Then later used

$change[$k] = "this";

It remains a single string instead of turning into an array. Is this a php.ini config I can change?

1

There are 1 answers

0
ficuscr On

As of 7.1 the behavior you describe changed. See change log for Assignment via string index access on an empty string

String modification by character on an empty string now works like for non-empty strings, i.e. writing to an out of range offset pads the string with spaces, where non-integer types are converted to integer, and only the first character of the assigned string is used. Formerly, empty strings where silently treated like an empty array.

<?php
$change='';
$change[2] = "this";
var_dump($change); 

/*
Prior to 7.1: 
  array(1) {
    [2]=>
    string(4) "this"
  }

7.1 and up:
  string(3) "  t"

PHP 7 has seen numerous improvements that make "stricter" typing possible and allow for better type hinting. PHP is still considered a loosely typed language though. Some examples include, as of 7.0, Scalar type declarations, Return type declarations and the strict_types directive.