How do I find the max length of a field (e.g. title field) I would like to retrieve the maximum length of a field programmatically, for instance the $node-&gt;title field .

I am writing a module that sets title and I don't really want to hard-code '255'. I am using Drupal 7.
The Drupal schema API has a function named drupal_get_schema (D7) or drupal_get_module_schema (D8) that lets you inspect a schema programatically and retrieve field constraints.

For instance, to get the maxlength of the title field in the {node} table, you can use the following in D7:

$schema = drupal_get_schema('node');
$maxlength = $schema['fields']['title']['length'];


You can also inspect the max length of any field used by Drupal simply by looking at the database schema that defines that field.  This will also tell you the names you need to use in the above PHP to get the right value in cases where you're unfamiliar with the schema.

For instance, if you are talking about the title field in the {node} table, you can see when looking at a scheme in a database inspection tool such phpMyAdmin that it is a varchar with a maximum length of 255 characters.