Organizational Research By

Surprising Reserch Topic

Question:how to remove one or more keys from an array using php



asked Sep 13, 2013 in PHP by rajesh
edited Sep 12, 2013
+1 vote
26 views



Related Hot Questions

1 Answer

0 votes

 

  
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." 
} 
*/ 
?>
 
answered Sep 13, 2013 by rajesh
edited Sep 12, 2013

...