Check if a Header Exists

You can check if a named header is present in a HeaderSet by calling its has() method.

To check if a header exists:

  1. Get the HeaderSet from the entity by via its getHeaders() method.
  2. Call the HeaderSet's has() method specifying the header you're looking for.

If the header exists, true will be returned or false if not.

Note: It's valid for some headers to appear more than once in a message (e.g. the Received header). For this reason has() accepts an optional numerical index, starting from zero to specify which header you want to check more specifically.

$headers = $message->getHeaders();

//Check if the To: header exists
if ($headers->has('To')) {
  echo 'To: exists';
}

//Check if an X-Foo header exists twice (i.e. check for the 2nd one)
if ($headers->has('X-Foo', 1)) {
  echo 'Second X-Foo header exists';
}

NOTE: Documentation for version 3 is in the wiki.