note 101422 modified in function.array-filter by danbrown

From: Date: Wed, 15 Dec 2010 19:20:06 +0000
Subject: note 101422 modified in function.array-filter by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-174965@lists.php.net to get a copy of this message
I built the following array_remove_keys() function to remove one or more keys from an array. <?php function array_remove_keys($array, $keys = array()) { // If array is empty or not an array at all, don't bother // doing anything else. if(empty($array) || (! is_array($array))) { return $array; } // If $keys is a comma-separated list, convert to an array. if(is_string($keys)) { $keys = explode(',', $keys); } // At this point if $keys is not an array, we can't do anything with it. if(! is_array($keys)) { return $array; } // array_diff_key() expected an associative array. $assocKeys = array(); foreach($keys as $key) { $assocKeys[$key] = true; } return array_diff_key($array, $assocKeys); } // Example: $data = array( 'name' => 'Brian', 'address1' => '98 Market St.', 'address2' => 'N/A' ); // Output before array_remove_keys() var_dump($data); // Remove address2 key. $data = array_remove_keys($data, 'address2'); // Output after array_remove_keys() var_dump($data); /* Output: array(3) { ["name"]=> string(5) "Brian" ["address1"]=> string(13) "98 Market St." ["address2"]=> string(3) "N/A" } array(2) { ["name"]=> string(5) "Brian" ["address1"]=> string(13) "98 Market St." } */ ?> --was-- I built the following array_remove_keys() function to remove one or more keys from an array. You can also find it on my blog at: http://www.reich-consulting.net/?p=429 <?php function array_remove_keys($array, $keys = array()) { // If array is empty or not an array at all, don't bother // doing anything else. if(empty($array) || (! is_array($array))) { return $array; } // If $keys is a comma-separated list, convert to an array. if(is_string($keys)) { $keys = explode(',', $keys); } // At this point if $keys is not an array, we can't do anything with it. if(! is_array($keys)) { return $array; } // array_diff_key() expected an associative array. $assocKeys = array(); foreach($keys as $key) { $assocKeys[$key] = true; } return array_diff_key($array, $assocKeys); } // Example: $data = array( 'name' => 'Brian', 'address1' => '98 Market St.', 'address2' => 'N/A' ); // Output before array_remove_keys() var_dump($data); // Remove address2 key. $data = array_remove_keys($data, 'address2'); // Output after array_remove_keys() var_dump($data); /* Output: array(3) { ["name"]=> string(5) "Brian" ["address1"]=> string(13) "98 Market St." ["address2"]=> string(3) "N/A" } array(2) { ["name"]=> string(5) "Brian" ["address1"]=> string(13) "98 Market St." } */ http://php.net/manual/en/function.array-filter.php

« previous php.notes (#174965) next »