Skip to content

Instantly share code, notes, and snippets.

@kidGodzilla
Last active August 29, 2015 14:27
Show Gist options
  • Save kidGodzilla/e94f6bea99dffd03e1fb to your computer and use it in GitHub Desktop.
Save kidGodzilla/e94f6bea99dffd03e1fb to your computer and use it in GitHub Desktop.
Deduce a value's type from a stringified version of that value
// Deduce Type
// James Futhey, 2015
//
// Useful for parsing a $_GET or $_POST value and knowing it's MySQL-compatible type
function deduceType ($value) {
if (strlen(strval($value)) === 0) {
return "null";
}
if ($value === "true" || $value === "false") {
return "boolean";
}
$type = "text";
if (is_numeric($value)) {
// We either have an int or float (decimal)
$type = "int";
if (!ctype_digit(strval($value))) {
$type = "decimal";
return $type;
}
} else {
// We either have a varchar, text, or datestring
if (strlen($value) < 256) {
$type = "varchar";
}
try {
if (new DateTime($value) !== FALSE) {
$type = "timestamp";
return $type;
}
} catch (Exception $e) {
return $type;
}
}
return $type;
}
@kidGodzilla
Copy link
Author

If you need to use this for anything other than SQL, you should return "float" instead of "decimal", and return "string" instead of "text" or "varchar".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment