0

How can I save an array, for example,

['name' => 'Some_name_1', 'Quantity' => 176],
['name' => 'some_name_2', 'Quantity' => 1096],
['name' => 'some_name_3', 'Quantity' => 1598],

from a foreach loop?

For example, I get those values from another array by applying the array_count_values() function in this form:

Array
(
    [Some_name_1] => 176
    [Some_name_2] => 1096
    [Some_name_3] => 1598
)

And when I apply the foreach() like this

foreach($values as $index => $value){
        $stats=['name'=>$index,'Quantity'=>$value];
    }

I only get one value stored in the new array and not the three ones.

Array
(
    [name] => Some_name_3
    [Quantity] => 1598
)

(Some_name_1, and Some_name_2 weren't stored in the array)

How can I save all of them inside the array? What am I missing?

1
  • 1
    $stats=['name'=>$index,'Quantity'=>$value]; to $stats[]=['name'=>$index,'Quantity'=>$value]; Commented Mar 9, 2016 at 23:41

2 Answers 2

1

push to the array, your syntax is incorrect.

foreach(values as $index=>$value)
{
    array_push($stats, array('name'=>$index, 'quantity'=>$value));
}

or as Matt says above, alternate syntax:

foreach(values as $index=>$value)
{
    $stats[] = array('name'=>$index, 'quantity'=>$value);
}
Sign up to request clarification or add additional context in comments.

Comments

1

Inside of your foreach loop you're not appending to an array - rather overwriting each time you iterate over the values array.

Append to an array rather than overwriting using the example below.

New function:

foreach($values as $index => $value){
        $stats[]=['name'=>$index,'Quantity'=>$value];
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.