Alex
Alex

Reputation: 68494

Remove oldest elements from a array

like

array(a, b, c, d, e);

I want to add new elements to it, but keep the maximum element count to 5. So if after the add the count exceeds 5, I want to remove elements from the start until the size of the array is 5 again.

Upvotes: 3

Views: 1503

Answers (9)

array_slice will help you

   $array = array('a','b','c','d','e');
    $array[] = 'f';

    if(count($array) > 5)
        $array = array_slice($array,count($array)-5);

    var_dump($array);

reusable function

function add_array_max(&$array,$item,$max)
    {
        $array[] = $item;
        if(count($array) > $max)
            $array = array_slice($array,count($array)-$max); 
    }

    add_array_max($array,'g',5);
    add_array_max($array,'h',5);
    add_array_max($array,'i',5);
    add_array_max($array,'j',5);

    var_dump($array);

Upvotes: 3

hakre
hakre

Reputation: 197775

For my suggestion I made use of array_sliceDocs:

Input:

$arr = range('a', 'c');
$new = 'f';
$highest = 4;

Code:

$arr = array_slice($arr, -$highest);
$arr[] = $new;

array_slice takes care to limit the array to the last 4 elements, then the new element is added.

If the array has less than 4 elements, this won't remove any elements, so only add the new one.

Demo

Upvotes: 3

Anonymous
Anonymous

Reputation: 3689

Try this:

if(count($array) >= 5)) { array_pop($array); }
array_push($array, 'whatever');

Upvotes: 1

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

Add elements in array and check following condition

if(count($arr) >= 5) {
   array_shift($arr); //remove element from beginning
}

Upvotes: 2

Jan Turoň
Jan Turoň

Reputation: 32912

function add($array,$item) {
  array_push($item);
  while(count($array)>5) array_shift($array);
}

Upvotes: 2

JB Nizet
JB Nizet

Reputation: 691755

From http://php.net/manual/en/language.types.array.php:

The unset() function allows removing keys from an array. Be aware that the array will not be reindexed. If a true "remove and shift" behavior is desired, the array can be reindexed using the array_values() function.

An example follows.

Upvotes: 1

Aurelio De Rosa
Aurelio De Rosa

Reputation: 22162

You can use this code:

$array = array('a', 'b', 'c', 'd', 'e');
$newElems = array ('f', 'g', 'h');

foreach($newElems as $elem)
{
   array_shift($array);
   array_push($elem);
}

It works as you can see here: http://codepad.org/DH2UUuTY

Upvotes: 1

chill
chill

Reputation: 16888

Use a circular buffer, overwriting old elements and remembering the index of the "first" one.

add_element (k)
  a [first] = k;
  first = (first + 1) % 5

access_element (i)
  return a [(first + i) % 5]

Upvotes: 1

Uladzimir Pasvistselik
Uladzimir Pasvistselik

Reputation: 3921

Try to use array_pad function. (see http://www.php.net/manual/en/function.array-pad.php) Or array_slice (see http://www.php.net/manual/en/function.array-slice.php)

Upvotes: 1

Related Questions