6

I have an array:

$array = [1,2,3,4,5,6,7,8];

How do I select a subset of the array, to return just [2,3,4,5,6]?

I think it should be something along the lines of:

$array[2-6]

but that's not working

4
  • 4
    use google and find array_slice on php.net Commented Jul 22, 2013 at 18:53
  • 1
    Googling php array subset -- first result = 'array_slice — Extract a slice of the array'. It makes me wonder why asking on SO is preferred to Googling :( Commented Jul 22, 2013 at 18:54
  • 1
    Sorry if you through this was a silly question. I am just learning PHP and didn't think of the word "subset" until I was writing this post. I did look for an answer online before posting. Commented Jul 22, 2013 at 19:00
  • +1 for the naïve (modern language thinking) [2-6] Commented Feb 27, 2014 at 14:18

4 Answers 4

13

You want to use array_slice($array, 1, 5)

http://php.net/manual/en/function.array-slice.php

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

2 Comments

Thanks everyone for the help - your responses were overwhelming. :)
To get the value without modifications in $array, you must use: array_slice($array, 1, 5, true) (cf. last parameter preserve_keys).
5

Use array_slice():

$array = [1,2,3,4,5,6,7,8];    
$output = array_slice($array, 1, 5);

print_r($output);

Output:

Array
(
    [0] => 2
    [1] => 3
    [2] => 4
    [3] => 5
    [4] => 6
)

Comments

1

You can use array_slice http://www.php.net/manual/en/function.array-slice.php

array_slice($array, 1,5);

Comments

0

Use array_filter

function filter_arr($value) {
    return 1 < $value && $value < 7;
}
array_filter($array, "filter_arr");

1 Comment

His attempted solution suggests that he's subsetting by index, not values.

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.