How to Remove Key from Array in Laravel

In PHP, when we need to remove a specific key from an array, such as when we have a password and confirm-password field but do not want to store the confirm-password field, we can use the unset() function. This function is a built-in PHP function that allows us to remove a specified key from an array.

In Laravel versions 6, 7, 8, 9, and 10, we can also use the array helper function to remove keys from an array. If you are working with Laravel, you can take advantage of this convenient array helper function. It enables us to remove multiple keys from a variable efficiently.

In Laravel, there is a predefined function called array_except() that allows us to remove specific keys from an array. Let's take a look at an example:

$data = [
   'username' => 'john_doe',
   'password' => 'secret',
   'email' => 'john@example.com',
   'confirm_password' => 'secret'
];

$filteredData = array_except($data, ['confirm_password']);
print_r($filteredData);
// After print this array value output is.

In this example, we have an array called $data with several key-value pairs. We want to remove the 'confirm_password' key from this array. By using the array_except() function and passing the array $data and the keys we want to exclude (in this case, ['confirm_password']), we get a filtered array called $filteredData.

Array
(
    [username] => john_doe
    [password] => secret
    [email] => john@example.com
)

As you can see, the 'confirm_password' key has been successfully removed from the array using the array_except() function.