How to rewrite array values in PHP arrays
Sep 10, 2020
PHP
beginners
beginners
PHP7
Purpose
- -Summary of how to update the values in the array contained in the array
Implementation environment
――I wrote this article while checking the operation of PHP on the following site. -https://paiza.io/ja
#Example
-
-The process to update the value of the array contained in the array is described below.
foreach (array A as & variable) { Variable ['index'] ='value you want to update'; }
Specific example of rewriting the data of the existing index of the associative array
-
-It is assumed that the associative array is stored in the array “$ infos”.
-
-In the associative array, the product ID is stored in the index “id”, the product name is stored in the index “item_name”, and the price of the product excluding tax is stored in the index “price”.
-
-How to withdraw the tax-excluded amount of the associative array index “price” stored in the array “$ infos”, calculate using the tax rate, and rewrite the tax-excluded amount of the associative array index “price” with the tax-included amount. Is described below.
<? php $ infos [] = [ 'id' => 1, 'item_name' =>'PHP book', 'price' => '1000', ];; $ infos [] = [ 'id' => 2, 'item_name' =>'Ruby book', 'price' => '1200', ];; foreach ($ infos as & $ info) { $ info ['price'] * = 1.1; } var_dump ($ infos); ?>
Specific example of adding a new index to an associative array
-
-It is assumed that the associative array is stored in the array “$ infos”.
-
-In the associative array, the product ID is stored in the index “id”, the product name is stored in the index “item_name”, and the price of the product excluding tax is stored in the index “price”.
-
-The method of withdrawing the tax-excluded amount of the index “price” of the associative array stored in the array “$ infos”, calculating using the tax rate, and adding the index “price_in_tax” to the associative array is described below.
<? php $ infos [] = [ 'id' => 1, 'item_name' =>'PHP book', 'price' => '1000', ];; $ infos [] = [ 'id' => 2, 'item_name' =>'Ruby book', 'price' => '1200', ];; foreach ($ infos as & $ info) { $ info ['price_in_tax'] = $ info ['price'] * 1.1; } var_dump ($ infos); ?>
#References
foreach ($ items as & $ item) {
$ item ['id'] = 123;
};