Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - get array records by index range

Tags:

arrays

php

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?

like image 769
user398341 Avatar asked Jan 17 '11 16:01

user398341


People also ask

How can we get particular data from array in PHP?

Answer: Use the Array Key or Index If you want to access an individual value form an indexed, associative or multidimensional array you can either do it through using the array index or key.

What does Array_splice () function do give an example?

The array_splice() function removes selected elements from an array and replaces it with new elements. The function also returns an array with the removed elements. Tip: If the function does not remove any elements (length=0), the replaced array will be inserted from the position of the start parameter (See Example 2).

What is the use of Array_flip () function?

The array_flip() function flips/exchanges all keys with their associated values in an array.


2 Answers

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); 
like image 129
polarblau Avatar answered Sep 28 '22 11:09

polarblau


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));
like image 33
bensiu Avatar answered Sep 28 '22 11:09

bensiu