Home >Backend Development >PHP Tutorial >How to Correctly Store Values from a foreach Loop into an Array in PHP?

How to Correctly Store Values from a foreach Loop into an Array in PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-12-12 19:24:09204browse

How to Correctly Store Values from a foreach Loop into an Array in PHP?

Storing Values from Foreach Loop into an Array

When iterating over data in a foreach loop, sometimes you may need to store the values into an array. However, simply assigning the value inside the loop often stores only the last value.

Example Code with Issue:

foreach($group_membership as $username) {
    $items = array($username);
}

print_r($items);

Solution:

To store all values, declare the array outside the loop and use $items[] to add each item:

$items = array();
foreach($group_membership as $username) {
    $items[] = $username;
}

print_r($items);

By following this modified code, the $items array will contain all the usernames from the $group_membership array, allowing you to work with them efficiently.

The above is the detailed content of How to Correctly Store Values from a foreach Loop into an Array in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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