Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inserting key value pair in associate multidimensional array in php

I have a multi dimensional array named $p_result which contains product related data now I want to add another key value element (with key "o_id" and value 4) into it using for each or for loop but so far I have tried this

foreach($p_result as $prod){
    $prod['o_id']=4;
}
print_r($p_result);

but its not adding [oid]=>4 into each of the array.print_r($p_result) shows

Array ( 
    [0] => Array ( [p_id] => 7 [quantity] => 122 [unitPrice] => 3 [subTotal] => 366 ) 
    [1] => Array ( [p_id] => 8 [quantity] => 133 [unitPrice] => 5 [subTotal] => 665 ) 
    )   
like image 429
Faisal Naseer Avatar asked Jun 30 '26 15:06

Faisal Naseer


2 Answers

Use as &$prod:

foreach($p_result as &$prod){
    $prod['o_id']=4;
}
print_r($p_result);
like image 192
Nick Avatar answered Jul 03 '26 03:07

Nick


You can do what you want by using the by reference operator &:

foreach($p_result as &$prod) {
    $prod['o_id']=4;
}

The reference operator allows you to access the parent variable because you are actually referring to the original variable.

Occasionally using reference can be problematic, in which case another option is:

foreach($p_result as $index => $prod) {
    $p_result[$index]['o_id']=4;
}
like image 32
random_user_name Avatar answered Jul 03 '26 04:07

random_user_name



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!