How to slice an array by key, not offset?

Martin picture Martin · May 22, 2013 · Viewed 15.1k times · Source

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
)

Answer

salathe picture salathe · May 22, 2013

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',
)