Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DRY - add certain number of elements to end of array until it's count reaches a specific int

Tags:

arrays

php

Due to a fairly old library I'm working with, I need to chunk up arrays into even chunks of five. So, if my array has 9 elements, I need to chunk it up (5 and 4) and then I need to add a blank element to the last array to get it to 5.

I have written some very bad code that works, but I'm aware that is goes against DRY principles because it counts the number, and uses multiple if statements to push the correct number of blank elements to get back up to 5.

Can anyone advise me how I should be breaking this code down so that $chunkFive is array_pushed to until it has 5 elements?

$blank = array("","","blank-image.png","",""); // create the blank image array
if(count($chunkFive) < 5){
    echo 'it contains less than five elements';
    if(count($chunkFive) == 4){
        echo 'insert one element'; // 4 present + array_push 1 = 5
        array_push($chunkFive,$blank);
    }else if(count($chunkFive) == 3){
        echo 'insert two elements'; // 3 present + array_push 2 = 5
        array_push($chunkFive,$blank);
        array_push($chunkFive,$blank);
    }else if(count($chunkFive) == 2){
        echo 'insert three elements'; // 2 present + array_push 3 = 5
        array_push($chunkFive,$blank);
        array_push($chunkFive,$blank);
        array_push($chunkFive,$blank);
    }else if(count($chunkFive) == 1){
        echo 'insert four elements';  // 1 present + array_push 4 = 5
        array_push($chunkFive,$blank);
        array_push($chunkFive,$blank);
        array_push($chunkFive,$blank);
        array_push($chunkFive,$blank);
    }
}else{
    echo 'it contains five elements'; // no need to adjust
    // do nothing
}
like image 293
user1486133 Avatar asked Nov 06 '15 10:11

user1486133


Video Answer


1 Answers

Use array_pad:

array_pad($chunkFive, 5, $blank);

e.g.:

[20] boris> $blank = ''; // easier to read ;-)
// ''
[21] boris> array_pad(array("one"), 5, $blank);
// array(
//   0 => 'one',
//   1 => '',
//   2 => '',
//   3 => '',
//   4 => ''
// )
[22] boris> 

The function exists since php 4 -- it normally pays off to use built in functions, as they are optimized c implementations in most cases.

like image 178
Tom Regner Avatar answered Sep 22 '22 15:09

Tom Regner