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_push
ed 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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With