2

In JS I would do something like this:

var arr = [];  
arr.push({ 
   sku : foo, 
   quantity: bar 
});

How do I do this with PHP? When I try to do this I'm getting a parsing error.

For example with PHP:

$someArray = array(); // or maybe someArray = []; ???
$someArray = array_push(
  'sku' => $sku,
  'quantity' => $quantity
);

Is this correct?

Thank you!

6
  • php.net/manual/en/function.array-push.php Commented Oct 12, 2017 at 16:15
  • thx for link, I checked this, but the prob is not with adding 1 value to the existing array. I'm having a trouble with the key/value pairs. Commented Oct 12, 2017 at 16:17
  • 1
    $someArray = array_push([ 'sku' => $sku, 'quantity' => $quantity ]); perhaps? Commented Oct 12, 2017 at 16:20
  • it looks like you are trying to pass an array into an array so you can array_merge() maybe. Commented Oct 12, 2017 at 16:21
  • $arrayName[] = $addItem; is faster than array_push Commented Oct 12, 2017 at 16:26

3 Answers 3

5

check this: array_push

you could do:

$array = [];
array_push($array, "item");

or

$array = [];
$item = "hi";
$array['key'] = $item;

or you could use

$array = [];
array_merge($array, ["abc" => 1]);

also your js code is equivilant to

$array = [];
array_push($array, ['item' => 'value', 'item1' => 'value1']);


// is equivalent to 
var arr = [];  
arr.push({ 
   sku : foo, 
   quantity: bar 
});
Sign up to request clarification or add additional context in comments.

Comments

2

No need for an array_push function. See ex:

$arr = [];
$arr['sku'] = $sku;
$arr['quantity'] = $quantity;

when handling key -> value pairs.

Edit (multidimensional one):

for($a=0; $a < $total ; $a++)
{    
  $arr[$a]['sku'] = $sku;
  $arr[$a]['quantity']  = $quantity;
}

2 Comments

I am looping over data and need to push them into the master array. The method you have described here will overwrite. I need to keep pushing each new sku/quantity into the master array.
Then I can think of two easy options. You can either insert the array to the master array after each iteration, or you can keep the data in a multi-dimensional array. Check my edit.
2

This was accomplished by the following:

array_push($someArray, ["sku" => $sku, "quantity" => $quantity]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.