0

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?

0stone0
  • 34,288
  • 4
  • 39
  • 64
carlo.borreo
  • 1,344
  • 2
  • 18
  • 35

2 Answers2

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

[ 'cost' => $cost, 'quantity' => $quantity, 'total_cost'  => $totalCost ] = $Item;
lukas.j
  • 6,453
  • 2
  • 5
  • 24
1

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);
Syscall
  • 19,327
  • 10
  • 37
  • 52