note 81208 deleted from function.array-push by peehaa
| From: | peehaa@php.net | Date: | Tue, 21 Mar 2017 08:38:59 +0000 |
| Subject: | note 81208 deleted from function.array-push by peehaa | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-208921@lists.php.net to get a copy of this message | ||
Note Submitter: darkimmortal at dkimmortal dot com
----
I wrote this function for use with 'latest scores' on a quiz site, but it has many
potential uses.
<?php
/**
* @desc array_push and removes elements from the beginning of the array until it is within limit
* @param array Array to push on to
* @param mixed Passed to array push as 2nd parameter
* @param int Limit (default = 10)
*
* @return array New array
*/
function array_push_limit($array,$add,$limit=10){
array_push($array, $add);
do {
array_shift($array);
$size=count($array);
} while($size > $limit);
return $array;
}
?>
----------
EXAMPLE:
----------
<?php
$array=array(1, -5, 23, -66, 33, 54, 3);
print_r(array_push_limit($array, "HELLO", 4));
?>
----------
OUTPUT:
----------
Array
(
[0] => 33
[1] => 54
[2] => 3
[3] => HELLO
)