2

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?

Dharman
  • 30,962
  • 25
  • 85
  • 135
D. Moore
  • 21
  • 2
  • There's no such config. Either declare variable as array or do not perform such type conversions. – u_mulder Sep 30 '20 at 21:33
  • 1
    Yes there were changes. As of 7.1 Now that would end up as `string(1) "t"`? [**Assignment via string index access on an empty string**](https://www.php.net/manual/en/migration71.incompatible.php#migration71.incompatible.empty-string-modifcation-by-character) – ficuscr Sep 30 '20 at 21:38
  • You could compare old versions behavior with https://3v4l.org/84hl3 And yes, they did change behavior in PHP 7 – Scuzzy Sep 30 '20 at 21:39
  • That makes sense because that was my result I guess I am just going to have to poke other variables and fix them as well – D. Moore Sep 30 '20 at 21:47

1 Answers1

4

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.

ficuscr
  • 6,975
  • 2
  • 32
  • 52