19

HI there,

Is there any PHP native function which returns the range of records from the array based on the start and end of the index?

i.e.:

array(0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd');

and now I would like to only return records between index 1 and 3 (b, c, d).

Any idea?

1

4 Answers 4

31

Couldn't you do that with e.g. array_slice?

$a = array(0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd');
array_slice($a, 1, 3); 
Sign up to request clarification or add additional context in comments.

Comments

15

there is a task for array_slice

array array_slice ( array $array , int $offset [, int $length [, bool $preserve_keys = false ]] )

example:

$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));

Comments

2

By using array_intersect_key

$myArray = array(0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd');
$arrayRange = array('1', '2', '3');

// this can also be used if you have integer only array values
// $arrayRange = range(1,3); 

$newArray = array_intersect_key($myArray, array_flip($arrayRange));

print_r($newArray);  // output: Array ( [1] => b [2] => c [3] => d )

Comments

-2
$array1 = array(1,2,3,4,5,6,23,24,26,21,12);

    foreach(range ($array1[0],$array1[5]) as $age){
        echo "Age: {$age}<br />";
    }

you should get the following output:

Age: 1

Age: 2

Age: 3

Age: 4

Age: 5

Age: 6

1 Comment

Downvote. This is a low-quality answer that will not be portable in non-consecutive cases. In this demo, you can see that your method fails miserably when there are gaps in the array values. range() fabricates values where there are no values in the array. Here is the flaw using your own input: Demo2 Please delete this answer. array_slice() and array_intersect_key() are the most sensible methods.

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.