How can the offset be correctly calculated in a PHP function that returns a part of an array?

When returning a part of an array in PHP, the offset needs to be correctly calculated to ensure that the desired subset of elements is returned. To calculate the offset, you can use the array_slice function along with the desired start index and length of the subset. Make sure to handle cases where the start index is out of bounds or negative to avoid errors.

function getArraySubset($arr, $start, $length) {
    if ($start < 0) {
        $start = max(0, count($arr) + $start);
    }
    
    return array_slice($arr, $start, $length);
}

// Example usage
$array = [1, 2, 3, 4, 5];
$start = 2;
$length = 2;

$result = getArraySubset($array, $start, $length);
print_r($result); // Output: [3, 4]