Shamshad Mansoori Shamshad Mansoori -4 years ago 51
PHP Question

Create a function which accepts an array and a defined length 6 and outputs array of length 2



/*1. Create a function which accepts an array and a defined length L and outputs array of length L


a) Input array properties;

1. It will have a fixed input maximum length ( N )
2. It will have few elements filled (upto length L )

The function should modify the array so that the remaining places of input array should be filled in with the already filled one in same order.
the function should output the modified array

For ex- 1. input array: [1,2] and Length: (L=6) (Total len:6, length of elements: 2)


  1. Output array should be [1,2,1,2,1,2]
    Another ex (for Length L=6)-inp arr: [1,2,3,4]O/p arr: [1,2,3,4,1,2]



[1,2,3]

(L=5) => [1,2,3,1,2]*/

Answer Source
$arr = [1, 2, 3, 6];

function arrayRepeat(&$array, $length)
{
    if($length <= count($array)) {
        $array = array_slice($array, 0, $length);
    } else {
        $addLength = $length - count($array);

        for($i = 0; $i < $addLength; $i++) {
            $array[] = $array[$i];
        }
    }
}

arrayRepeat($arr, 6);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download