22

PHP function array_slice() returns sequence of elements by offset like this:

// sample data
$a = array('a','b','c',100=>'aa',101=>'bb',102=>'cc'); 

// outputs empty array because offset 100 not defined
print_r(array_slice($a,100));

Current function arguments:

array_slice ( $array, $offset, $length, $preserve_keys) 

I need something like this:

array_slice ( $array, **$key**, $length, $preserve_keys) 

That outputs this according to above print_r:

array (
   100 => aa,
   101 => bb,
   102 => cc
)
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Martin Ille
  • 6,747
  • 9
  • 44
  • 63

3 Answers3

19

To find the offset of the key, use array_search() to search through the keys, which can be retrieved with array_keys(). array_search() will return FALSE when the specified key (100) is not present in the array ($a).

$key = array_search(100, array_keys($a), true);
if ($key !== false) {
    $slice = array_slice($a, $key, null, true);
    var_export($slice);
}

Prints:

array (
  100 => 'aa',
  101 => 'bb',
  102 => 'cc',
)
salathe
  • 51,324
  • 12
  • 104
  • 132
9

Returns parts of $array whose keys exist in the array $keys:

array_intersect_key($array,array_flip($keys));
CragMonkey
  • 808
  • 1
  • 11
  • 22
3

Alternative solution

If you want to slice the array by using keys for the items you want to get, you could use the following custom function to do so:

function array_slice_keys($array, $keys = null) {
    if ( empty($keys) ) {
        $keys = array_keys($array);
    }
    if ( !is_array($keys) ) {
        $keys = array($keys);
    }
    if ( !is_array($array) ) {
        return array();
    } else {
        return array_intersect_key($array, array_fill_keys($keys, '1'));
    }
}

Usage:

$ar = [
    'key1' => 'a',
    'key2' => 'b',
    'key3' => 'c',
    'key4' => 'd',
    'key5' => 'e',
    'key6' => 'f',
];

// Get the values from the array with these keys:
$items = array_slice_keys( $ar, array('key2', 'key3', 'key5') );

Result:

Array
(
    [key2] => b
    [key3] => c
    [key5] => e
)
Philip
  • 2,888
  • 2
  • 24
  • 36
  • Why is `$keys` an optional argument? It seems odd that this function handles so many defensive cases of getting no keys, getting an array without keys, getting... an empty array? – GuyPaddock Apr 26 '19 at 03:09
  • 2
    +1 I prefer this over `array_search` answer because it's easier to add more keys this way. But you could've just answered `array_intersect_key($array, array_fill_keys($keys, '1'))` without the (unnecessary) function. – YTZ Jul 13 '19 at 12:44