Today’s article, we will remove multiple elements by key in a PHP array. Using PHP we can delete multiple keys from an Array.
In PHP there is no built in method to achieve this, but we can combine several PHP functions to achieve this.
In this article we will be demonstrating two methods to remove multiple keys from PHP array.
Method 1 : unset method
Below code we are removing two keys (hobby, like) from the array using unset method
$customer = [ 'name'=>'John Doe', 'email'=>'[email protected]', 'street'=>'Street 1, Avenue Drive', 'city'=>'Texas', 'hobby' => 'Reading', 'country' => 'US', 'like' => 'Fishing' ]; $toRemove = ['hobby', 'like']; foreach($toRemove as $key){ unset($customer[$key]); } print_r($customer);
Method 2 Using combination of array_diff_key and array_flip
$removeFields = ['hobby', 'like']; $newCustomer = array_diff_key($customer, array_flip($removeFields)); print_r($newCustomer);
Did this post help you?
Tutsplanet brings in-depth and easy tutorials to understand even for beginners. This takes a considerable amount of work. If this post helps you, please consider supporting us as a token of appreciation:
- Just want to thank us? Buy us a Coffee
- May be another day? Shop on Amazon using our links.
Your prices won't change but we get a small commission.