tags:

views:

103

answers:

4
+2  Q: 

PHP - Add to Array

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

+8  A: 

Loop across the array and use references to modify it:

foreach ($products as &$v) {
  $v['SKU'] = 1234;
}
cletus
Removed downvote as the code is now fixed (Initially $v wasn't a reference)
Yacoby
Thanks so much!
moose2004
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.
Frank Farmer
+2  A: 
foreach ( $products as &$arr )
    $arr['SKU'] = 1234;
aefxx
+1  A: 

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.

Yacoby
+3  A: 
foreach ($products as $k=>$v){
    $v['SKU']=1234;
    $products[$k]=$v;
}
print_r($products);
ghostdog74
Or, you can replace the lines inside the loop with a single one: `$products[$k]['SKU']=1234;`
Frank Farmer