Eamonn
Eamonn

Reputation: 418

Grab array values with keys in specified range - PHP 5.5

In an array of arbitrary order and keys, as below

$myArray = array(
    1  => 'foo',
    4  => 'bar',
    6  => 'foobar',
    24 => 'barfoo',
    30 => 'fizz',
    35 => 'buzz',
    50 => 'fizzbuzz'
);

How can I get a segment of the array by a key range, for example, every item with a key between 5 and 40

Something like array_range($myArray, 5, 40);

Expected output: array(6 => 'foobar', 24 => 'barfoo', 30 => 'fizz', 35 => 'buzz')

This is similar to How to use array_filter() to filter array keys? but in this case, I am restricted to PHP 5.5.

Upvotes: 2

Views: 199

Answers (3)

Progrock
Progrock

Reputation: 7485

Just iterate the array, and use a condition to build a filtered array (here assuming an inclusive range):

<?php
$in = array(
    1  => 'foo',
    4  => 'bar',
    6  => 'foobar',
    24 => 'barfoo',
    30 => 'fizz',
    35 => 'buzz',
    50 => 'fizzbuzz'
);

$out = [];
foreach($in as $k => $v)
{
    if($k >= 5 && $k <= 40) {
        $out[$k] = $v;
    }
}
var_dump($out);

Output:

array (size=4)
  6 => string 'foobar' (length=6)
  24 => string 'barfoo' (length=6)
  30 => string 'fizz' (length=4)
  35 => string 'buzz' (length=4)

Upvotes: 1

AbraCadaver
AbraCadaver

Reputation: 78994

Define a range of keys in an array and then compute the intersection of keys:

$range  = array_flip(range(5, 40));
$result = array_intersect_key($myArray, $range);

One liner:

$result = array_intersect_key($myArray, array_flip(range(5, 40)));

Optionally to fill the range array (I just thought of the other one first and it's shorter):

$range = array_fill_keys(range(5, 40), 1);

If you want specific keys and not a range, just define an array of keys or values and flip:

$range = array_flip(array(6, 24, 50));
//or
$range = array(6=>1, 24=>1, 50=>1);

Upvotes: 3

random_user_name
random_user_name

Reputation: 26160

If PHP version is under 5.6, upgrade your version of PHP - 5.5 is not even supported any longer. If you can't upgrade PHP, then clearly AbraCadaver's answer is the one to use.

This requires PHP 5.6+, but was answered before the PHP version was clarified in the question, so I will leave it for reference.

Using array_filter - so long as the PHP version is above 5.6:

$allowed_range = [ 'min' => 5, 'max' => 40 ];
$filtered = array_filter(
    $myArray,
    function ( $key ) use ( $allowed_ranged ) {
        return ( $key >= $allowed_range[ 'min' ] && $key <= $allowed_range[ 'max' ] );
    },
    ARRAY_FILTER_USE_KEY
);

Upvotes: 2

Related Questions