From 202c02f988786ed40a111e24969d30bd2f3d81cb Mon Sep 17 00:00:00 2001 From: danieliser Date: Wed, 3 Jul 2013 21:55:08 -0400 Subject: [PATCH] Added function Arr::extract_existing() Similar to extract except that it doesnt return keys that arnt set in the first array. EX.. Arr::filter( array('a' => 'foo', 'b' => 'bar'), array('a','c') ); Returns array('a' => 'foo') Key b is removed from results altogether. This is particularly useful for extracting fields from $_POST for Model without leaveing unset values as NULL. Regular extract in this situation will end up saving value "C" above as NULL even if your only attempting to change "A". --- classes/Kohana/Arr.php | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/classes/Kohana/Arr.php b/classes/Kohana/Arr.php index 479b72f6c..81605febb 100644 --- a/classes/Kohana/Arr.php +++ b/classes/Kohana/Arr.php @@ -303,7 +303,31 @@ public static function extract($array, array $paths, $default = NULL) return $found; } - + + /** + * Retrieves multiple keys from an array only if they exist. + * + * // Get the values "a", "b" from $arr = array('a' => 'foo', 'b' => 'bar', c => 'car') + * $result = Arr::extract_existing($arr, array('a', 'b')); + * returns array('array('a' => 'foo', 'b' => 'bar') + * + * @param array array to filter keys from + * @param array list of key names to search for + * @return array + */ + public static function extract_existing($array, array $keys) + { + $found = array(); + foreach ($keys as $key) + { + if(isset($array[$key])) + { + $found[$key] = $array[$key]; + } + } + return $found; + } + /** * Retrieves muliple single-key values from a list of arrays. *