Search code examples
phparraysvariable-types

PHP 7.2 is_array not eval to true


All, I have a class with some variables defined at the top like so:

var $conditionStyle = '';

Later I can style one thing like this:

$this -> conditionStyle = 'someStyle';

Or multiple things like this:

$this->conditionStyle[$this->styleRowsCount] = 'someStyle';

Next I would see if conditionStyle was an array or not like so:

if(is_array($this-> conditionStyle) {...}

In php 7.0 and earlier this evaluated fine. With 7.2 I have to use settype() or it fails to evaluate correctly. Is this an issue with 7.2 or did 7.2 correct a deficiency in the previous versions?


Solution

  • PHP 7.1 changed the behavior of this code:

    $x = '';
    $x[3] = 'foo';
    

    In < 7.1, $x is:

    array (
       3 => 'foo',
    )
    

    while in >= 7.1, it's:

    string '   f'
    

    See it online at 3v4l.org.

    This change is poorly mentioned in the PHP 7.1 Release Notes:

    The empty index operator is not supported for strings anymore
    Applying the empty index operator to a string (e.g. $str[] = $x) throws a fatal error instead of converting silently to array.

    The PR that made this change also had the side effects you are noticing, and as someone else commented in the Notes section of that page.

    You should initialize your variable to an array at the outset to work in all versions.