Changing PHP Array Values in a Foreach Loop (Duplicate Fix)
In multidimensional arrays, traversing through each element using a foreach loop can present complexities when attempting to modify the original array.
Consider the following example:
$fields = [ "names" => [ "type" => "text", "class" => "name", "name" => "name", "text_before" => "name", "value" => "", "required" => true, ] ];
Now, suppose you have a function that checks if required inputs are filled in:
function checkForm($fields) { foreach ($fields as $field) { if ($field['required'] && strlen($_POST[$field['name']]) <= 0) { $fields[$field]['value'] = "Some error"; // Here's the issue } } return $fields; }
The problematic line is $fields[$field]['value'] = "Some error";. To modify the original array, you need to access the key of the current element instead of the value, as shown below:
foreach ($fields as $key => $field) { if ($field['required'] && strlen($_POST[$field['name']]) <= 0) { $fields[$key]['value'] = "Some error"; } }
Note the use of $key within $fields[$key]['value'] to reference the key of the current element in the outer loop. This ensures that the original array is modified as intended.
The above is the detailed content of How Can I Correctly Modify PHP Array Values Within a Foreach Loop?. For more information, please follow other related articles on the PHP Chinese website!