diff --git a/php/src/cl.php b/php/src/cl.php index a1073ee..ebbcca9 100644 --- a/php/src/cl.php +++ b/php/src/cl.php @@ -60,6 +60,35 @@ class cl { return $default; } + /** + * retourner la valeur à l'index $index, ou $default si le tableau est null + * ou vide, ou si l'index n'existe pas + * + * ici, l'index est le rang de la clé: 0 pour la première clé du tableau, 1 + * pour la deuxième, etc. + * + * si $index est négatif, il est compté à partir de la fin du tableau + */ + static final function nth(?iterable $iterable, int $index, $default=null) { + if ($iterable === null) return $default; + if ($index < 0 && !is_array($iterable)) { + $iterable = iterator_to_array($iterable, false); + } + if (is_array($iterable)) { + $keys = array_keys($iterable); + $count = count($keys); + while ($index < 0) $index += $count; + $key = $keys[$index] ?? null; + if ($key === null) return $default; + return $iterable[$key]; + } + foreach ($iterable as $value) { + if ($index === 0) return $value; + $index--; + } + return $default; + } + /** * retourner la dernière valeur de $array ou $default si le tableau est null * ou vide diff --git a/php/src/db/_private/_select.php b/php/src/db/_private/_select.php index 80b0460..1e7f1d0 100644 --- a/php/src/db/_private/_select.php +++ b/php/src/db/_private/_select.php @@ -23,7 +23,8 @@ class _select extends _common { return preg_match("/^select\b/i", $sql); } - private static function add_prefix(string $col, ?string $prefix): string { + private static function add_prefix(?string $col, ?string $prefix): string { + $col ??= "null"; if ($prefix === null) return $col; if (strpos($col, ".") !== false) return $col; return "$prefix$col";