skip to Main Content

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:OneDriveworkTornpm.php on line 27

Notice: Undefined offset: 0 in D:OneDriveworkTornpm.php on line 27
PHP Notice:  Undefined offset: 1 in D:OneDriveworkTornpm.php on line 27

Notice: Undefined offset: 1 in D:OneDriveworkTornpm.php on line 27
PHP Notice:  Undefined offset: 2 in D:OneDriveworkTornpm.php on line 27

Notice: Undefined offset: 2 in D:OneDriveworkTornpm.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?

2

Answers


  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);
    
    Login or Signup to reply.
  2. $Item = [
        'cost'       => 45800,
        'quantity'   => 500,
        'total_cost' => 22900000,
    ];
    
    [ 'cost' => $cost, 'quantity' => $quantity, 'total_cost'  => $totalCost ] = $Item;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search