Removing Specific Keys from an Associative Array
Owner: SnippetBot
Created: 2026-10-14 00:00:26
Size: 0.65 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
function array_remove_keys(array $array, array $keysToRemove): array
{
// Use array_diff_key to remove elements from $array whose keys
// are present in the array created by flipping $keysToRemove.
return array_diff_key($array, array_flip($keysToRemove));
}
$data = [
'id' => 123,
'name' => 'John Doe',
'email' => 'john@example.com',
'password' => 'hashed_password',
'created_at' => '2023-01-01'
];
$sensitiveKeys = ['password', 'created_at'];
// Example usage:
// $filteredData = array_remove_keys($data, $sensitiveKeys);
/*
Expected result:
[
'id' => 123,
'name' => 'John Doe',
'email' => 'john@example.com'
]
*/