setReturnKey()

Sets a custom key to index the result array. This is especially useful for fast lookup tables or dropdown sources.

Signature:

public function setReturnKey(string $key): self

Default Example (no key set)

// No return key defined – result is numerically indexed
$users = $db->get('test_users', null, 'cID, name');
print_r($users);

/* Output:
[
  0 => ['cID' => 123, 'name' => 'Alice'],
  1 => ['cID' => 142, 'name' => 'Bob'],
  2 => ['cID' => 245, 'name' => 'Charlie']
]
*/
Warning: The specified return key must be unique. If duplicate values are encountered, only the last row will be retained for that key.
Note: This feature only applies to array and object output modes. When using json via setOutputMode('json'), the return key is ignored.

Example with setReturnKey('cID')

// Set return key to 'cID' – result is keyed by cID
$db->setReturnKey('cID');
$users = $db->get('test_users', null, 'cID, name');
print_r($users);

/* Output:
[
  123 => ['cID' => 123, 'name' => 'Alice'],
  142 => ['cID' => 142, 'name' => 'Bob'],
  245 => ['cID' => 245, 'name' => 'Charlie']
]
*/
Deprecated: The method $db->map() is deprecated and has been removed in v1.5.x.
Use Instead: setReturnKey() is the instance-safe replacement for map(). Unlike the old static behavior, this method ensures correct results across multiple connections and concurrent requests.

Use Cases

  • Key-value lists for dropdowns or selects
  • Efficient lookups by ID or unique field
  • Prevent re-indexing after fetch

See Also