开发者

PHP array : renumber elements when new element added

I have a PHP array with elements:

$myarray = array ( "tom", "dick", "Harry" );
开发者_高级运维

. I need to keep the array fixed in size of just 3 elements . I need to add a new element "jerry" such that the array now looks like

 $myarray = array ( "jerry", "tom", "dick");

so in a way I am moving the elements along and the 4th one drops out, with the newest element going at the beginning. I could write all of this by hand, renumbering the elements etc etc.

I just wondered if there was a quicker way to do this though.

Many thanks! J


One way to do this is to utilize array_pop and array_unshift:

# Pop the last element off the array
array_pop($myarray);

# Insert the new value
array_unshift($myarray, "jerry");

Or, you can use array_merge and array_slice:

$myarray = array_merge(array("jerry"), array_slice($myarray, 0, 2));

Both of these methods reset the keys, so they will be renumbered from 0 to 2.


You might want to have a look at SplQueue. On every addition of a new element, check whether the number of elements is higher than x and dequeue if necessary.


$myarray = array ( "tom", "dick", "Harry" );
array_pop( $myarray ); //remove the last element
array_unshift( $myarray, "jerry" ); //prepend the new element
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜