1

I'm using PHP 5.4 and trying to add dictionary-style complex values to an array thusly:

array_push($qbProductsArray, $qbProduct => $authNetAmount);

I get this error:

Parse error: syntax error, unexpected '=>'

My desired result is to have a series of $qbProduct and $authNetAmount that are related together. I don't want to add them separately like this:

array_push($qbProductsArray, $qbProduct, $authNetAmount);

...because those 2 values are related to each other, and I don't want them just all thrown in together, even though they are adjacent. I want a firmer link between them. How can this be done?

Leonardo Henriques
  • 784
  • 1
  • 7
  • 22
HerrimanCoder
  • 6,835
  • 24
  • 78
  • 158
  • why not $qbProductsArray[$qbProduct] = $authNetAmount ? – PedroFaria99 Mar 07 '18 at 14:45
  • 1
    can you not simply combine these into an array? e.g `array_push($qbProductsArray, [$qbProduct => $authNetAmount])` – Juakali92 Mar 07 '18 at 14:45
  • 1
    You can't have `=>` outside of an array context. Those variables are simply function arguments. – M. Eriksson Mar 07 '18 at 14:45
  • It's not helpful to create a 2d array with an indexed first level and try to use it like a "dictionary". https://stackoverflow.com/q/19670485/2943403 You need associative first level keys so that you can quickly reference whatever value by its key. The accepted answer should not be implemented in your project (or anyone else's). – mickmackusa May 18 '23 at 23:38

2 Answers2

1

try adding them as array:

array_push($qbProductsArray, array($qbProduct => $authNetAmount));

using the => syntax outside of the context of array is not possible in PHP.

man0v
  • 654
  • 3
  • 13
  • And now getting to the nested values within a loop is puzzling me: `Array ( [0] => Array ( [HGS-SUB] => SimpleXMLElement Object ( [0] => 59.00 ) ) [1] => Array ( [DOMN-MTH] => SimpleXMLElement Object ( [0] => 25.00 ) ) ) ` -- how to get HGS-SUB and 59, for example?? – HerrimanCoder Mar 07 '18 at 14:56
  • HGS-SUB will be `$array_name[0]['HGS-SUB']` which is an array as well. The element that is holding 59.00 is `$array_name[0]['HGS-SUB'][0]`. However, bear in mind that this value is stored in a `SimpleXMLElement` Object, which is not an array. – man0v Mar 07 '18 at 15:20
0

You can try this,

$a = array();

for($i = 0; $i < 10; $i++){
    $a[$i] = $i."1";
}

print_r($a);

//Output:

Array
(
    [0] => 01
    [1] => 11
    [2] => 21
    [3] => 31
    [4] => 41
    [5] => 51
    [6] => 61
    [7] => 71
    [8] => 81
    [9] => 91
)

echo $a[0];

//Output:

01
Jaikishore
  • 111
  • 2
  • 6