Search code examples
phparraysassociative-arraymerging-data

Parse error while using array_push() to add associative elements to an array


I am having trouble with array_push. It is displaying "Parse error: syntax error, unexpected T_DOUBLE_ARROW" The variable $vars is an associative array for paypal.

array_push(
    $vars,
    'item_number' . $num => $id,
    'item_name' . $num => $cart_item->name,
    'amount_' . $num => $cart_item->discount_price,
    'quantity_' . $num => $value
);
$vars = array (
    'cmd' => '_cart',
    'charset' => 'utf-8',
    'upload' => '1',
    'currency_code' => 'HKD',
    'amount' => $_SESSION['total'],
    'custom' => $user_data->id
);

Solution

  • The => syntax is only valid when you define an array. array_push can only be used to push elements with auto-incrementing numeric keys.

    Maybe you could use array_merge: http://www.php.net/manual/en/function.array-merge.php

    $vars = array_merge( $vars, array(
        'item_number'.$num => $id,
        'item_name'.$num => $cart_item->name,
        'amount_'.$num => $cart_item->discount_price,
        'quantity_'.$num => $value
    ));
    

    Or you could use the + operator, thought it behaves quite differently from array_merge: + operator for array in PHP?

    $vars =  $vars + array(
        'item_number'.$num => $id,
        'item_name'.$num => $cart_item->name,
        'amount_'.$num => $cart_item->discount_price,
        'quantity_'.$num => $value
    );