Home > Backend Development > PHP Tutorial > How Can I Modify Array Values Within a Foreach Loop in PHP?

How Can I Modify Array Values Within a Foreach Loop in PHP?

DDD
Release: 2024-11-29 09:36:11
Original
561 people have browsed it

How Can I Modify Array Values Within a Foreach Loop in PHP?

Modifying Array Values Using Foreach Loop

To modify an array's values during a foreach loop, you need to address the correct memory location. The typical foreach loop iterates over a copy of the values, which can lead to unexpected results when trying to modify the original array.

Solution 1: Direct Memory Reference

To modify the array values directly, you can use a reference (&) before the $value variable in the foreach loop. This ensures that you are modifying the original array's memory location, rather than a copy.

foreach ($bizaddarray as &$value) {
    $value = strip_tags(ucwords(strtolower($value)));
}
unset($value); // Remove the reference
Copy after login

Solution 2: Accessing Values from Source Array

Alternatively, you can access the original array values using the key in the foreach loop. This method is particularly useful when dealing with associative arrays.

foreach ($bizaddarray as $key => $value) {
    $bizaddarray[$key] = strip_tags(ucwords(strtolower($value)));
}
Copy after login

By using either of these methods, you can permanently modify the array values during the foreach loop, ensuring that the stripped tags remain removed when converting the array to a string.

The above is the detailed content of How Can I Modify Array Values Within a Foreach Loop in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template