1

I have an array with a dynamic number of elements (it's a list of words generated by users).

I would like to be able to divide the array elements by 3 at anytime:

My thoughts were to count the elements in the array (using count($myArray)) and if the modulus != 0 I would recursively add elements until it does.

Here is my code:

function adjustArray($myArray, $lineLimit = 3){
    $count = count($myArray);

    if ($count % $lineLimit != 0):
        $myArray[] = '';
        adjustArray($myArray, $lineLimit);

    else:
        return $myArray; //problem when returning is conditional (return won't work - returns NULL
    endif;

}

How can I fix this code, or better yet, how can I do this more efficiently?

3
  • 1
    "how can I do this more efficiently" --- it's not suitable for the broken code. How can you write more efficiently a broken code? Put your cat on the keyboard - it will generate some for you. Commented Jan 7, 2013 at 1:09
  • Anyway, your explanation isn't clear enough Commented Jan 7, 2013 at 1:10
  • what i meant was how can i get the results i want using a more efficient method :) obviously not with the current code ;) Commented Jan 7, 2013 at 1:16

2 Answers 2

1

You don't need recursion here. Simply add the number of elements needed in order to make the length a multiple of 3:

function adjustArray($myArray, $lineLimit = 3){
    $count = count($myArray);

    if ($count % $lineLimit != 0){
        for($i = 0; $i < $lineLimit - $count % $lineLimit; $i++)
            $myArray[] = "";
    }   

    return $myArray;
}

Here is a demonstration: http://codepad.org/6viL1peq

Alternatively, you could use:

$myArray = array_merge($myArray, array_fill(0, $lineLimit - $count % $lineLimit, ""));

instead of a loop, to make it even faster.

A demonstration of this approach can be found here.

Sign up to request clarification or add additional context in comments.

Comments

1

Do it in a while loop so you don't have the overhead of making function calls.

while(count($myArray) % $lineLimit !=0){
  $myArray[] = '';
}

1 Comment

Thanks so much for your quick response! Asad bead you to it (so i marked his as correct)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.