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
Release: 2024-12-12 19:24:09
Original
217 people have browsed it

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);
Copy after login

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);
Copy after login

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template