Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
From a PDO Statement, fetch all the results and store them in an associative array, mapping integer and float values to PHP int and float types. It reads the column metadata to read the value's type.
// Returns the contents of $stm (PDO Statement)
// as an associative array, with correct native types
// for integers, nulls, and floats
$array = [];
while ($fila = $stm->fetch(\PDO::FETCH_ASSOC)) {
$i = 0;
$columnMetas = [];
while ($columnMeta = $stm->getColumnMeta($i)) {
$columnMetas[$columnMeta['name']] = $columnMeta;
foreach ($fila as $key => $value) {
if ($value === null) {
$columnMeta = $columnMetas[$key];
switch ($columnMeta['native_type']) {
case 'LONG':
case 'TINY':
$fila[$key] = intval($value);
case 'DOUBLE':
$fila[$key] = floatval($value);
$array[] = $fila;
return $array;

This comment has been minimized.

Copy link
Owner Author

@AeonFr AeonFr commented Aug 16, 2019

Note: Tested in PHP 5.6 and MySQL 15.0 (10.0 MariaDB)

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