Henrik Petterson
Henrik Petterson

Reputation: 7094

Limit multidimensional array to X arrays inside

I have a multidimentional array like this:

$my_array = array(

    array($user_id, $id, $type, $log, $url, $timestamp),
    array($user_id, $id, $type, $log, $url, $timestamp),
    array($user_id, $id, $type, $log, $url, $timestamp),
    // and so on...
);

$my_array has a random amount of arrays inside. I want to limit the amount of arrays to 5 inside $my_array. How can I achieve this? So, if there are 5 arrays inside, and one more is added, then remove the last array...

Upvotes: 1

Views: 151

Answers (2)

user488187
user488187

Reputation:

Just use a function to add arrays to it, then do your checks. E.g

function addToArray($arr, $newValue, $limit=5) {
    if (count($arr) >= $limit) {
        array_shift($arr);
    }
    $arr[] = $newValue;

    return $arr;
}

The function array_shift removes the first element and returns the shortened array.

If it is possible for things to be added to the array outside of this function, you can generalize:

function addToArray($arr, $newValue, $limit=5) {
    while (count($arr) >= $limit) {
        array_shift($arr);
    }
    $arr[] = $newValue;

    return $arr;
}

EDIT: Added improvements suggested by Jonathan Kuhn.

Upvotes: 2

Jonathan Kuhn
Jonathan Kuhn

Reputation: 15301

Add the new value and then call array_slice.

If you want to add to the end of the array:

//array with more than 5
$array = range(1, 8);  // [1, 2, 3, 4, 5, 6, 7, 8]
//add the element
$array[] = 9;
//get the last 5
$array = array_slice($array, -5);

//output: [5, 6, 7, 8, 9]

http://codepad.viper-7.com/DL91ZK

If you want to add to the beginning of the array

//array with more than 5
$array = range(1, 8); // [1, 2, 3, 4, 5, 6, 7, 8]
//add to the array
array_unshift($array, 0);
//get the first 5
$array = array_slice($array, 0, 5);

//output: [0, 1, 2, 3, 4]

http://codepad.viper-7.com/RGfohJ

Upvotes: 1

Related Questions