Home >Backend Development >PHP Tutorial >How Can I Modify Original Array Values in a PHP Foreach Loop?
Modifying Original Array Values with PHP Foreach Loop
When working with multidimensional arrays in PHP, it's sometimes necessary to modify the original array within a foreach loop. However, accessing the name of the current array (e.g., "names" in your provided example) can be confusing.
To address this issue, PHP allows passing arrays by reference using the "&" operator. This ensures that modifications made to the array within the loop are reflected in the original array.
Revised Code Using Passing by Reference:
function checkForm(&$fields){ foreach($fields as &$field){ if($field['required'] && strlen($_POST[$field['name']]) <= 0){ $field['value'] = "Some error"; } } return $fields; }
Benefits of Passing by Reference:
Cautionary Advice:
The above is the detailed content of How Can I Modify Original Array Values in a PHP Foreach Loop?. For more information, please follow other related articles on the PHP Chinese website!