Laravel 5: Excluding Items From an Array With except

April 11, 2018 —John Koster

The except helper method will return all the key/value pairs of the $array where the keys in the original array are not in the $keys array.

#Signature

The signature of the except method is:

1public static function except(
2 $array,
3 $keys
4);

#Example Use

The following examples assume that the $_POST super-global contains the following information:

1array {
2 ["first_name"] "John"
3 ["last_name"] "Doe"
4 ["password"] "some_password"
5}

We could easily get all the information except for the password like so:

1use Illuminate\Support\Arr;
2 
3$inputData = Arr::except($_POST, 'password');

$inputData would then contain the following items:

1array {
2 ["first_name"] "John"
3 ["last_name"] "Doe"
4}

When passing a single item, such as password, for the $keys parameter, it will be converted to an array automatically.

Passing an array would look like this:

1use Illuminate\Support\Arr;
2 
3// This would only return an array with the user's `last_name`.
4$inputData = Arr::except($_POST, ['password', 'first_name']);

#Global array_except Helper Function

The array_except function is a shortcut to calling Arr::except. This function is declared in the global namespace.

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.