50

I want to get an array composed of the first 4 rows of the original array $arr,

how to do it in PHP?

0

3 Answers 3

93

array_slice()

$subArray = array_slice($arr,0,4);
Sign up to request clarification or add additional context in comments.

4 Comments

What if I don't know the offset ?
@JCharette - then you need to identify the offset, using functions like array_search() perhaps.... but that would depend entirely on what you needed to do, and is an entirely different question
it resets the keys, not worked for me. Thanks
$output = array_slice($arr, 0, 1, true); solved my issue and preserves the keys also. Thanks.
18

You need to use array_slice().

$output = array_slice($arr, 0, 4);

2 Comments

it resets the keys, not worked for me. Thanks
$output = array_slice($arr, 0, 1, true); solved my issue and preserves the keys also. Thanks.
9

Check this out.. this should help

<?php
$input = array("a", "b", "c", "d", "e");

$output = array_slice($input, 2);      // returns "c", "d", and "e"
$output = array_slice($input, -2, 1);  // returns "d"
$output = array_slice($input, 0, 3);   // returns "a", "b", and "c"

// note the differences in the array keys
print_r(array_slice($input, 2, -1));
print_r(array_slice($input, 2, -1, true));
?>

From http://docs.php.net/array_slice.

1 Comment

When posting code from another source, you should always paste the link in too.

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.