How to store values from foreach loop into an array

0 votes

The code below does not work, only stores the last value, tried $items .= ..., but that is not doing the trick either, any help will be appreciated.

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

print_r($items);
Aug 31, 2020 in PHP by kartik
• 37,530 points
5,416 views

1 answer to this question.

0 votes

Hello @kartik,

Declare the $items array outside the loop and use $items[] to add items to the array:

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

print_r($items);

Hope it helps!!
Thank you!!

answered Aug 31, 2020 by Niroj
• 82,820 points

Related Questions In PHP

0 votes
1 answer

How to return an array from an AJAX call?

Hello, Php has a function for this, just ...READ MORE

answered Nov 8, 2020 in PHP by Niroj
• 82,820 points
527 views
0 votes
1 answer

How to return an array from an AJAX call?

Hello @kartik, Use JSON to transfer data types (arrays and ...READ MORE

answered Nov 14, 2020 in PHP by Niroj
• 82,820 points
2,959 views
0 votes
1 answer

How to pass an array within a query string?

Hello, Submitting multi-value form fields, i.e. submitting arrays ...READ MORE

answered Apr 7, 2020 in PHP by Niroj
• 82,820 points
7,568 views
0 votes
1 answer

How to concatenate text from multiple rows into a single text string in SQL server?

Hello @kartik, Use COALESCE: DECLARE @Names VARCHAR(8000) SELECT @Names = ...READ MORE

answered Jul 21, 2020 in PHP by Niroj
• 82,820 points
1,649 views
+1 vote
1 answer

How to make anchor tag with routing using Laravel?

Hey @kartik, First you have to go to ...READ MORE

answered Mar 18, 2020 in Laravel by Niroj
• 82,820 points
9,429 views
0 votes
1 answer

What is redirection in Laravel?

Named route is used to give specific ...READ MORE

answered Mar 18, 2020 in Laravel by Niroj
• 82,820 points
1,044 views
0 votes
1 answer

How to install Laravel via composer?

Hello, This is simple you just need to ...READ MORE

answered Mar 23, 2020 in Laravel by Niroj
• 82,820 points
846 views
+1 vote
1 answer

What are named routes in Laravel and How can specify route names for controller actions?

Hey @kartik, Named routing is another amazing feature of ...READ MORE

answered Mar 23, 2020 in Laravel by Niroj
• 82,820 points
10,500 views
0 votes
1 answer

How to remove duplicate values from an array in PHP?

Hello @kartik, Use array_unique(): Example: $array = array(1, 2, 2, 3); $array ...READ MORE

answered Sep 15, 2020 in PHP by Niroj
• 82,820 points
998 views
0 votes
1 answer

How to delete object from array inside foreach loop?

Hello @kartik, Use this: foreach($array as $elementKey => $element) ...READ MORE

answered Sep 15, 2020 in PHP by Niroj
• 82,820 points
3,135 views