One thing you do not want to do is assume that every key in your array is numeric and that it accurately represents the offset of each element. This is wrong, because PHP arrays are not like traditional arrays. The array key is not the offset of the element (i.e. it does not determine the order of elements) and it does not have to be a number.
Unfortunately, PHP arrays are ordered hashmaps, not traditional arrays, so the only way to insert a new element in the middle of the map is to create a brand new map.
You can do this by using PHP's array_chunk() function, which will create a new array of elements, each containing up to a designated number of elements, form your input array. Thus we create an array of arrays or chunks of elements. This way you can iterate over the chunks and append them to a new array, getting your desired effect.
$names = array( "Ayush" , "Vaibhav", "Shivam", "Hacker", "Topper",
"ABCD", "NameR", "Tammi", "Colgate", "Britney",
"Bra", "Kisser");
$addthis = "ADDTHIS";
$result = array();
foreach (array_chunk($names, 3) as $chunk) { // iterate over each chunk
foreach ($chunk as $element) {
$result[] = $element;
}
// Now push your extra element at the end of the 3 elements' set
$result[] = $addthis;
}
If you wanted to preserve keys as well you can do this....
$names = array( "Ayush" , "Vaibhav", "Shivam", "Hacker", "Topper",
"ABCD", "NameR", "Tammi", "Colgate", "Britney",
"Bra", "Kisser");
$addthis = "ADDTHIS";
$result = array();
foreach (array_chunk($names, 3, true) as $chunk) { // iterate over each chunk
foreach ($chunk as $key => $element) {
$result[$key] = $element;
}
// Now push your extra element at the end of the 3 elements' set
$result[] = $addthis;
}
This perserves both order of the elements as well as keys of each element. However, if you don't care about the keys you can simply use the first example. Just be careful that numeric keys in order will cause you a problem with the second approach since the appended element in this example is assuming the next available numeric key (thus overwritten on the next iteration).