Generate a list of IPv6 addresses within a given range

<?php
// https://stackoverflow.com/a/55521768/1255289
// Generate a list of IPv6 addresses within a given range

function expand_ipv6(string $ip): ?string
{
    // https://stackoverflow.com/a/12095836/1255289
    $hex = unpack("H*", inet_pton($ip))[1] ?? "";
    return (strlen($hex) === 32) ? implode(":", str_split($hex, 4)) : null;
}

$IpStart_v6_FromDb = "2001:db8::1234";
$IpEnd_v6_FromDb = "2001:db8::1299";

$ip1 = expand_ipv6($IpStart_v6_FromDb);
$ip2 = expand_ipv6($IpEnd_v6_FromDb);
if ($ip1 === null || $ip2 === null) {
    die;
}

// https://stackoverflow.com/a/35838357/1255289
// length is 39 to account for 7 colons
for ($i = 0; $i < 39 && $ip1[$i] === $ip2[$i]; $i++);

$ipv6_prefix = substr($ip1, 0, $i);
$ipv6_start = hexdec(substr($ip1, $i));
$ipv6_end = hexdec(substr($ip2, $i));

if (strlen($ipv6_prefix) < 26) {
    // adjust this to requirements to prevent too large ranges
    die;
}

for ($a = $ipv6_start; $a <= $ipv6_end; $a++) {
    $hex = dechex($a);
    printf("%s%s\n", $ipv6_prefix, implode(":", str_split($hex, 4)));
}