Hi. I'm Pedro and I'm from Portugal.

I've been working with php for a while but only now i decided to try my
luck and propose a new array function that will become handy for many
people :)

This function adds new elements to the end of an array but limits the
amount of total elements it can have, by eliminating the oldest entries.

*Example:*
Array limit: 4
1, 2, 3, 4 -> 4 elements

When you try to add a fifth element:
2, 3, 4, 5 -> $ elements

The good thing is that, even if you in the middle decide to limit the array
to 10, it will store 10 elements but if you decide to put an inferior array
limit, it will remove the oldest entries until the limit size is achieved.

Example:
Limit 6 elements:
1, 2, 3, 4, 5, 6 -> 6 elements

Limit 3
When you try to add a new element:
5, 6, 7 -> 3 elements

The function is written bellow:

function array_push_limited(&$arrayValues, $newElement, $limit){
$count = count($arrayValues);
 if($count == 0){
$arrayValues[0] = $newElement;
}
else if($count < $limit){
array_push($arrayValues, $newElement);
}
else if ($count == $limit) {
array_shift($arrayValues);
array_push($arrayValues, $newElement);
}
else if ($count > $limite) {
do{
array_shift($arrayValues);
} while(count($arrayValues) > $limit - 1);
array_push($arrayValues, $newElement);
}
}

I have some more proposals but in time, after I improve them, I will send
an email with them.

I hope you see an advantage into put this as an array function for php.

*Regards,*
*Pedro Pereira*

Reply via email to