How to Remove Multiple Keys from PHP Array

AuthorSumit Dey Sarkar

Pubish Date28 Jan 2024

categoryPHP

In this tutorial, we will learn how to remove multiple keys from PHP array.

How to Remove Multiple Keys from PHP Array

How to remove multiple elements by key in PHP array

To remove multiple keys from a PHP array, you can use the unset() function for each key you want to remove.

Here's an example:

<?php
// Sample array
$myArray = array(
    'key1' => 'value1',
    'key2' => 'value2',
    'key3' => 'value3',
    'key4' => 'value4',
);

// Keys to remove
$keysToRemove = array('key2', 'key4');

// Remove keys from the array
foreach ($keysToRemove as $key) {
    unset($myArray[$key]);
}

// Display the modified array
print_r($myArray);
?>

In this example, the unset() function is used inside a loop to remove each key specified in the $keysToRemove array. After the loop, you can print or use the modified array as needed.

Please note that this method modifies the original array in place. If you want to keep the original array and create a new array without the specified keys, you can use functions like array_diff_key():

<?php
// Sample array
$myArray = array(
    'key1' => 'value1',
    'key2' => 'value2',
    'key3' => 'value3',
    'key4' => 'value4',
);

// Keys to remove
$keysToRemove = array('key2', 'key4');

// Create a new array without the specified keys
$newArray = array_diff_key($myArray, array_flip($keysToRemove));

// Display the new array
print_r($newArray);
?>

In this case, array_diff_key() creates a new array that contains all the elements from the original array except those with keys specified in $keysToRemove.

Comments 0

Leave a comment