Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

array_diff_key

Returns the elements of the first array whose keys are absent from the others.

Syntax

array_diff_key(array $array, array ...$arrays): array

Parameters

ParameterTypeDescription
$arrayarrayThe array to take elements from.
...$arraysarrayThe arrays whose keys are compared against.

Return value

arrayThe elements with unique keys.

Examples

Removing service fields from data:

<?php
 
$user = ['name' => 'Anna', 'password' => 'secret', 'token' => 'abc'];
 
echo json_encode(array_diff_key($user, array_flip(['password', 'token'])));

Output:

{"name":"Anna"}

Notes

Only the keys are compared — the values do not matter.

See also

  • array_diff — Returns the values of the first array that are absent from the others.
  • array_intersect_key — Returns the elements of the first array whose keys are present in the others.

In the tutorial

  • Array functions — Processing arrays in PHP without loops — array_map, array_filter, array_reduce, searching and slicing.

Thanks for reading!

Donate to the site — we work hard for you.