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);
Sep 1, 2020 in PHP by kartik
• 37,520 points
29,844 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 Sep 1, 2020 by Niroj
• 82,880 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,880 points
3,008 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,880 points
17,209 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 8, 2020 in PHP by Niroj
• 82,880 points
12,252 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,880 points
3,023 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,880 points
22,847 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,880 points
2,923 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,880 points
2,860 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,880 points
44,127 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,880 points
2,688 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,880 points
7,053 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP