Voting

: nine minus one?
(Example: nine)

The Note You're Voting On

bishop
20 years ago
Sometimes you need to pick certain non-integer and/or non-sequential keys out of an array. Consider using the array_pick() implementation below to pull specific keys, in a specific order, out of a source array:

<?php

$a
= array ('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4);
$b = array_pick($a, array ('d', 'b'));

// now:
// $a = array ('a' => 1, 'c' => '3');
// $b = array ('d' => 4, 'b' => '2');

function &array_pick(&$array, $keys)
{
if (!
is_array($array)) {
trigger_error('First parameter must be an array', E_USER_ERROR);
return
false;
}

if (! (
is_array($keys) || is_scalar($keys))) {
trigger_error('Second parameter must be an array of keys or a scalar key', E_USER_ERROR);
return
false;
}

if (
is_array($keys)) {
// nothing to do
} else if (is_scalar($keys)) {
$keys = array ($keys);
}

$resultArray = array ();
foreach (
$keys as $key) {
if (
is_scalar($key)) {
if (
array_key_exists($key, $array)) {
$resultArray[$key] = $array[$key];
unset(
$array[$key]);
}
} else {
trigger_error('Supplied key is not scalar', E_USER_ERROR);
return
false;
}
}

return
$resultArray;
}

?>

<< Back to user notes page

To Top