简体   繁体   中英

Get subset of array based on values in PHP

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.

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 )

See https://eval.in/926983

Try array_chunk

array_chunk($array,4,true);

First parameter array

Second parameter size

Third parameter preserve keys

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM