Łukasz D. Tulikowski Łukasz D. Tulikowski - 1 month ago 7
PHP Question

Returning “n” elements from array disturbed evenly generates stderr

I have a solution which takes

m-element array
returns an
n-element array
distributed evenly. But for some value of m it generates
stderr
.

For example, if array will have 15 elements it
stderr
will be:


  • PHP Notice: Undefined offset: -3

  • PHP Notice: Undefined offset: -1



  • class SpredArrayClass
    {

    var $array = [1,2,3,4,5,6,7,8,9,9,10,11,12,13,14,15];

    function spreadOutArray(array $array = [], $targetOutputLength = 10) {

    $array = $this->array;

    $originalArrayLength = count($array);

    if ($originalArrayLength == 0) {
    return false;
    }

    if ($originalArrayLength <= $targetOutputLength) {
    return $array;
    }

    $output = [];
    $interval = round($originalArrayLength / $targetOutputLength);
    for ($index = $originalArrayLength - 1; count($output) < $targetOutputLength; $index -= $interval) {
    $output[] = $array[$index];
    }

    return array_reverse($output);
    }
    }


    Problem seem to be in this part:

    $output = [];
    $interval = round($originalArrayLength / $targetOutputLength);
    for ($index = $originalArrayLength - 1; count($output) < $targetOutputLength; $index -= $interval) {
    $output[] = $array[$index];
    }


    Undefinded offset stderr
    appears at this line:
    $output[] = $array[$index];


    Demo of code execution here: http://ideone.com/UrF9UK

    Answer

    Your Problem stems from the the condition in your for Loop. Change it to this:

            $output = [];
            $interval = round($originalArrayLength / $targetOutputLength);
    
            // JUST KEEP LOOPING & PUSHING TILL SO LONG AS $index IS GREATER THAN 0;
            for($index = $originalArrayLength - 1; $index>=0; $index -= $interval) {
                $output[] = $array[$index];
            }
    
    Comments