Last active
August 29, 2015 14:27
-
-
Save kidGodzilla/e94f6bea99dffd03e1fb to your computer and use it in GitHub Desktop.
Deduce a value's type from a stringified version of that value
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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".