'PHP list() expects numerical indexes in v7.4.6 [duplicate]

In the PHP manual, I read:

Before PHP 7.1.0, list() only worked on numerical arrays and assumes the numerical indices start at 0.

My code:

echo 'Current PHP version: ' . phpversion() . "\n" ;
print_r( $Item ) ;
list( $Cost, $Quantity, $TotalCost ) = $Item ;

Output:

Current PHP version: 7.4.6
Array
(
    [cost] => 45800
    [quantity] => 500
    [total_cost] => 22900000
)
PHP Notice:  Undefined offset: 0 in D:\OneDrive\work\Torn\pm.php on line 27

Notice: Undefined offset: 0 in D:\OneDrive\work\Torn\pm.php on line 27
PHP Notice:  Undefined offset: 1 in D:\OneDrive\work\Torn\pm.php on line 27

Notice: Undefined offset: 1 in D:\OneDrive\work\Torn\pm.php on line 27
PHP Notice:  Undefined offset: 2 in D:\OneDrive\work\Torn\pm.php on line 27

Notice: Undefined offset: 2 in D:\OneDrive\work\Torn\pm.php on line 27

It seems to me that this version of PHP expects that the indexes are numerical, even if v7.4.6 should be greater than v7.1.0. Am I missing something?



Solution 1:[1]

$Item = [
    'cost'       => 45800,
    'quantity'   => 500,
    'total_cost' => 22900000,
];

[ 'cost' => $cost, 'quantity' => $quantity, 'total_cost'  => $totalCost ] = $Item;

Solution 2:[2]

list() does not work with associative arrays, because list() wait for an array with numeric keys.

You could use array_values($Item):

$Item=[
    'cost'       => 45800,
    'quantity'   => 500,
    'total_cost' => 22900000,
];

list($Cost, $Quantity, $TotalCost) = array_values($Item);

// or equivalent, with array destructuring:
[$Cost, $Quantity, $TotalCost] = array_values($Item);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 lukas.j
Solution 2 Syscall