PHP 8.1 : Deprecate autovivification on false
16, April 2022

Autovivification means automatic creation of array (or hash) when we try to assign a new element to a non-array variable. In such case, PHP will create an array as if it was defined as array originally. For example:

<?php

$notexists['key'] = 'value';
// php will create $notexists even though it didn't exist
print_r($notexists);
// Array ( [key] => value )

// same thing for null variable
$nullvar = null;

$nullvar['key'] = 'value';
// php will create $nullvar as array even though was null
print_r($nullvar);
// Array ( [key] => value )


// PHP even does it for false value
$var = false;

$var['key'] = 'value';
print_r($var);
// Array ( [key] => value )


Umm, excuse me?

Yes, I know. But this is actually a considered as cool thing in PHP since it is a dynamic weakly typed language anyway. Specially when you are building an nested array inside a loop, autovivification helps us lazy developers to ignore defining the variable first. Less typing, less bugs, right? Right??


But what about:

function get_user()
{
    $stmt = $pdo->query("SELECT * FROM users WHERE id = 1");

    return $stmt->fetch();
}

$user = get_user();

$user['has_seen_new_promo'] = true;

Aha, Above code might cause problem if for some reason get_user() couldn't find a user and returns false. We were being naive and assigned another value to $user without checking if we have valid $user at all. $user is not an array, depending on what we do with it later might cause huge issue in our app, maybe even a security breach.

Thankfully, PHP doesn't allow this with other scalar types (true, int, "").


But can't we fix it?

We can, partially. While PHP won't/can't fix the null variable case, because undefined variable and null variable is not so different in PHP, and PHP developers love to ignore defining the variable first. But PHP 8.1 has solved the false autovivification. It is now deprecated to assign array element to a false variable. PHP 9 will remove this feature entirely.

$var = false;

$var['key'] = 'value';
// Automatic conversion of false to array is deprecated


RFC: https://wiki.php.net/rfc/autovivification_false


Write comment about this article: