How to remove key from array in Laravel?

In this tutorial, we will explain how to remove a key from an array in Laravel. Sometimes, we need to delete specific keys from an array, such as the ‘name’ and ‘password’ fields, because we don’t need to store them, In such cases, we can use PHP’s predefined ‘unset()’ function to remove these keys from the input array.

In Laravel, there are several methods laravel remove key from array. One of the easiest method is to use the ‘unset()’ function. Here’s how you can delete a key from an array.

1. Remove key from array using unset() function

This function is a built-in PHP function that allows us to remove a specified key from an array.

$myArray1 = ['name' => 'test', 'password' => '12345', 'type' => 1];

  unset($myArray1['name']);
  unset($myArray1['password']);
2. Remove key from array using array_except() function

If you work with Laravel, you can use the array helper functions. One useful function is ‘array_except()’, which allow you to remove multiple keys from an array. Below, we explain how to use this predefined Laravel function with an example

Example 1:
$myArray1 = ['name' => 'Jasminkumar', 'password' => '12345', 'type' =>1];

$resultData = array_except($myArray1, ['name', 'password']);

print_r($resultData);
Example 2:

This function is a predefined Laravel function that allow us to remove multiple key from an array.

$myArray1 = ['name' => 'Jasminkumar', 'password' => '12345', 'type' => 1];

$resultData = Arr::except($myArray1, ['name', 'password']);

print_r($resultData);
3. Remove key from array using array_diff_key() function

If you want to remove multiple keys from array, you can use the array_diff_key() function along with array_flip().

Example:
$myArray1 = ['name' => 'Jasminkumar', 'password' => '12345', 'type' => 1];

$resultData = array_diff_key($myArray1, array_flip(['name', 'password']));

print_r($resultData);
4. Remove key from array using array_filter() function

Another method to remove keys with specific values is to use array_filter() to filter out certain elements.

Example:
$myArray1 = ['name' => 'Jasminkumar', 'password' => '12345', 'type' => 1];

$resultData = array_filter($myArray1, function ($value, $key) {
    return $key != 'type';
}, ARRAY_FILTER_USE_BOTH);

print_r($resultData);
5. Remove key from array using array_splice() for indexed arrays.

For indexed array (arrays with numeric keys), you can use array_splice() to remove an element on index.

Example:
$myArray1 = ["Red", "Yellow", "black"];

//Remove the Yellow element (index 1, 'yellow')
array_splice($myArray1, 1, 1);

dd($myArray1);

I hope this tutorial help you.