Fri, 07 Nov 2008

Convert 15-character Salesforce IDs to 18-characters IDs with PHP

Saleforce uses 15-character IDs as primary keys for every record. When retrieving an ID over the API, 18-character case-insensitive IDs are returned. Generally, this doesn't cause any problems because the 18-character version can be used anywhere the 15-character one is. One problem arises though when you are storing IDs in a text field. In this case, you may need to convert a 15-character ID into its 18-character version. Salesforce provides a description of how to perform this conversion.

Here is a PHP implementation of the algorithm.

function sf15to18($short) {
   $chunks = str_split($short, 5);
   $extra = '';
   foreach ($chunks as $chunk) {
      $chars = str_split($chunk, 1);
      $bits = '';
      foreach ($chars as $char) {
         $bits .= (!is_numeric($char) && $char == strtoupper($char)) ? '1' : '0';
      }
      $map = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ012345';
      $extra .= substr($map, base_convert(strrev($bits), 2, 10), 1);
   }
   return $short . $extra;
}

tech » salesforce | Permanent Link

The state is that great fiction by which everyone tries to live at the expense of everyone else. - Frederic Bastiat