Well, this has been quiet for a while. So I'm going to share a routine I knocked together to emulate sliced array views. The fun of array elements that contain variable references. I've pulled this stunt before....
function slice(array &$input, int $start = 0, int $end = PHP_INT_MAX, int $step = 1): array
{
$start = max($start, 0);
$end = min($end, count($input));
$step = max($step, 1);
$return = [];
for($i = $start; $i < $end; $i += $step)
{
$return[] = &$input[$i];
}
return $return;
}
// Examples
$array = range(0,20);
echo "\n\n";
echo 'Original array: ', join(' ', $array), "\n";
$pick = slice($array, 2, 12, 3);
echo 'Picking every third item starting from 2 up to 12: ', join(' ', $pick), "\n";
$pick[3] = 'foo!';
echo 'Changed one item: ', join(' ', $pick), "\n";
echo 'Original array now looks like: ', join(' ', $array), "\n";
echo "\n\n";
$again = slice($array, start: 4, step: 5); // Note: PHPv8 named arguments because they're nice.
echo 'Every fifth item starting from 4 and continuing to the end: ', join(' ', $again), "\n";
foreach($again as &$poke)
{
$poke = 'wibble';
}
unset($poke);
echo 'Answer every question the same way: ', join(' ', $again), "\n";
echo 'Making the original array: ', join(' ', $array), "\n";
// And variable references are symmetric, so
$array[19] = 'Yeah';
echo join(' ', $again), " you can go the other way as well.\n\n";
// These views are live.
// And just a little more elaborate...
$stride = 9;
$rows = array_fill(0, $stride**2, 0);
$columns = [];
for($i = 0; $i < $stride; ++$i)
{
$columns[] = slice($rows, $i, step: 9); // Variable references survive this sort of treatment.
}
$columns = array_merge(...$columns); // And this sort too; we're not actually touching the array elements themselves
for($i = 0; $i < $stride**2; ++$i)
{
$columns[$i] = $i;
}
echo join(' ', $rows);
/*
The same result can be achieved with
$stride = 9;
$rows = array_merge(...array_map(null, ...array_chunk(range(0, $stride**2-1), $stride)));
but that would be missing the point.
*/
?>