user398341
user398341

Reputation: 6577

PHP - get array records by index range

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?

Upvotes: 19

Views: 33929

Answers (4)

Mukesh Chapagain
Mukesh Chapagain

Reputation: 25958

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 )

Upvotes: 2

Kaiser
Kaiser

Reputation: 145

$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

Upvotes: -2

bensiu
bensiu

Reputation: 25564

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

Upvotes: 15

polarblau
polarblau

Reputation: 17734

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

Upvotes: 31

Related Questions