Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add another item after every 10 in an array

I have an array:

$names = [
    "Ayush" , "Vaibhav", "Shivam",
    "Hacker", "Topper", "ABCD",
    "NameR", "Tammi", "Colgate",
    "Britney", "Bra", "Kisser"
];

And I have another variable

$addthis = "ADDTHIS";

How to make an array from these two so that after every three items in $names, the value of $addthis is added. So, I want this array as result from these two.

$result = [
    "Ayush", "Vaibhav", "Shivam", "ADDTHIS",
    "Hacker", "Topper", "ABCD", "ADDTHIS",
    "NameR", "Tammi", "Colgate", "ADDTHIS",
    "Britney", "Bra", "Kisser"
];
like image 313
Ayush Mishra Avatar asked Nov 04 '22 08:11

Ayush Mishra


1 Answers

"Oneliner", just for fun:

$new = array_reduce(
    array_map(
        function($i) use($addthis) { return count($i) == 3 ? array_merge($i, array($addthis)) : $i; },
        array_chunk($names, 3)
    ),
    function($r, $i) { return array_merge($r, $i); },
    array()
);
like image 96
zerkms Avatar answered Nov 08 '22 13:11

zerkms