phpmysqlphp-5.6php-7.1

Created arrays in PHP 5.6 with [] work, but in PHP 7.1 give fatal error


In PHP 5.6 this works fine, but in PHP 7.1 it gives Fatal error: Uncaught Error: [] operator not supported for strings

$result->execute();
$result->bind_result($id, $name);   
while($result->fetch()){
    $datos[]=array(
        $id => $name
    );
}

Solution

  • As of PHP 7.1, when you access a non-array variable (in this case a string) like an array, a fatal error will be thrown.

    Initialize the array first, with $datos = [];. This will overwrite anything you have set earlier, and explicitly set this variable as an array:

    $result->execute();
    $result->bind_result($id, $name);
    $datos = [];
    while($result->fetch()){
        $datos[]=array(
            $id => $name
        );
    }
    

    If you're trying to create an array of $id => $name, the following code should work:

    $result->execute();
    $result->bind_result($id, $name);
    $datos = [];
    while($result->fetch()){
        $datos[ $id ] = $name;
    }