1

How do I add to the end of each sub array? Here is an example.

$products = array( 
 array( Code => 'TIR', 
  Description => 'Tires', 
  Price => 100 
 ),
 array( Code => 'OIL', 
  Description => 'Oil', 
  Price => 10 
 ),
 array( Code => 'SPK', 
  Description => 'Spark Plugs', 
  Price =>4 
 ) 
);

I want to add SKU=>1234 after Price in each array. Thanks

0

5 Answers 5

8

Loop across the array and use references to modify it:

foreach ($products as &$v) {
  $v['SKU'] = 1234;
}
Sign up to request clarification or add additional context in comments.

1 Comment

One thing to be wary of when using this technique: don't try to re-use $v in a second loop (without first calling unset($v)), or you'll end up with some very confusing behavior -- you'll end up overwriting $products[2], in this example. To protect against this, I'm in the habit of immediately unset()ting the reference immediately after the completion of the loop... just in case any code below ever decides it wants to use the same variable name.
3
foreach ($products as $k=>$v){
    $v['SKU']=1234;
    $products[$k]=$v;
}
print_r($products);

1 Comment

Or, you can replace the lines inside the loop with a single one: $products[$k]['SKU']=1234;
2
foreach ( $products as &$arr )
    $arr['SKU'] = 1234;

Comments

1

Loop over the array using a reference (Note the ampersand before the $val):

foreach ( $products as &$val ){
    $val['SKU'] = 1234;
}

That way rather than $val being a copy of the array element, it is a reference to the value, so altering it alters the value held in $products.

Comments

0

For completeness, functional iteration can be used to append the new element to all rows to create a new array.

Code: (Demo)

$new = ['SKU' => 1234];
var_export(
    array_map(fn($row) => $row + $new, $products)
);

Or use functional iteration to modify by reference instead of returning the data. Demo

$new = ['SKU' => 1234];
array_walk($products, fn(&$row) => $row += $new);
var_export($products);

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.