Php – “Cut” an element by its key from an array

arraysPHP

I've got an indexed array with n elements:

Array(
    'key1'     => 'value1',
    'key2'     => 'value1',
    'key3'     => 'value1',
    ...
    'key<i-1>' => 'value<i-1>',
    'key<i>'   => 'value<i>',
    'key<i+1>' => 'value<i+1>',
    ...
    'key<n>'   => 'value<n>'
)

How to "cut" (ie: copy + remove) the i_th element so the result array is:

Array(
    'key1'     => 'value1',
    'key2'     => 'value1',
    'key3'     => 'value1',
    ...
    'key<i-1>' => 'value<i-1>',
    'key<i+1>' => 'value<i+1>',
    ...
    'key<n>'   => 'value<n>'
)

I know the array_pop() and array_shift() PHP functions, but is there a generic one to "cut" an element by its key?

Thank you.

Best Answer

You can use the following code to retrieve then remove an element at it's index:

function array_cut(&$array, $key) {
  if(!isset($array[$key])) return null;

  $keyOffset = array_search($key, array_keys($array));
  $result = array_values(array_splice($array, $keyOffset, 1));
  return $result[0];
}

You can then use it as such:

echo "Numerically Index Test:\n";

$a = array(0,1,2,3,4,5,6);
echo array_cut($a, 2) . "\n";
var_dump($a);

echo "------------------------------\n";

echo "Assosiative Index Test:\n";

$b = array('hello' => 'world', 'how' => 'like that', 'where' => 'Stack Overflow');
echo array_cut($b, 'how') . "\n";
var_dump($b);

Outputs:

Numerically Index Test:
2
array(6) {
  [0]=>
  int(0)
  [1]=>
  int(1)
  [2]=>
  int(3)
  [3]=>
  int(4)
  [4]=>
  int(5)
  [5]=>
  int(6)
}
------------------------------
Assosiative Index Test:
like that
array(2) {
  ["hello"]=>
  string(5) "world"
  ["where"]=>
  string(14) "Stack Overflow"
}