Reputation: 3731
I have an array like the below one
Array
(
[0] => 1
[1] => 1
[2] => 1
[3] => 2
[4] => 2
[5] => 3
[6] => 3
[7] => 3
[8] => 4
[9] => 4
[10] => 4
)
Is there any way to get a subset of this array using the values? So that, if need the subset of value 1, then it has to display
Array
(
[0] => 1
[1] => 1
[2] => 1
)
And if subset of 2 then
Array
(
[3] => 2
[4] => 2
)
And so on.. I need to preserve the index too.
I searched so many places. But didn't get an answer for this. I wish to avoid the multiple looping for this.
Upvotes: 1
Views: 949
Reputation: 17434
You can use array_filter
to filter an array down to only the elements you're looking for. Set $subset
to whatever value you're searching for, and it'll return the matching elements, without changing the keys.
$subset = 2;
$results = array_filter($array, function ($item) use ($subset) {
return $item === $subset;
});
print_r($results);
Array ( [3] => 2 [4] => 2 )
Upvotes: 6
Reputation: 1076
Try array_chunk
array_chunk($array,4,true);
First parameter array
Second parameter size
Third parameter preserve keys
Upvotes: 0