1

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.

1
  • How do you calculate subset? Commented Dec 28, 2017 at 12:39

2 Answers 2

6

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

Sign up to request clarification or add additional context in comments.

1 Comment

Wow.. and that is simply a great solution. Thank you
0

Try array_chunk

array_chunk($array,4,true);

First parameter array

Second parameter size

Third parameter preserve keys

1 Comment

Thanks for your time. But this will make the chunks with constant length. In my case, the length could not determine.

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.