The $wpdb query methods return all query results as strings. For example, an 'ID' column would return a string value like '42' instead of an integer 42.
Is there a way to configure the WP database class to make the database content types match to PHP types? Or do I need to continue to do this manually like below?
$results = $wpdb->get_results('SELECT * FROM my_table');
foreach ($results as $result)
{
// All integer values
foreach (array('id', 'user_id', 'comment_count') as $field)
{
$result->$field = (int) $result->$field;
}
// All float values
foreach (array('price') as $field)
{
$result->$field = (float) $result->$field;
}
// All boolean values
foreach (array('is_open', 'is_confirmed') as $field)
{
$result->$field = (bool) $result->$field;
}
// Etc.
}
Why bother, you may think? Well, for starters, clean code is fun to work with. Integer values should not be stored as strings. When you create a custom function to look up something, a product, for example, I like to be able to differentiate the field to look up based on the data type of the passed argument:
function load_product($id_or_slug)
{
if (is_int($id_or_slug))
{
// Look up by ID
}
else
{
// Look up by slug
}
}
is_numeric()? I gave this some thought and I got few ideas how to convert to proper types, but I can't stop thinking that it would just be a waste of code and resources.'-1.2e3'is numeric too, but that's not the point. Without the proper types you can't write code that relies on the type. In many/most cases it probably won't matter; it just feels ugly to me.