Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: how to 'cut' my array?

Tags:

I have an array

Array
(
    [0] => 0
    [1] => 1
    [2] => 2
    [3] => 3
    [4] => 4
    [5] => 5
)

How can I remove the latest 2 cells and make it shorter ?

Array
(
    [0] => 0
    [1] => 1
    [2] => 2
)

Thanks

like image 344
aneuryzm Avatar asked Aug 27 '10 15:08

aneuryzm


People also ask

How do you end an array in PHP?

You can use the end() function in PHP to get the last element of any PHP array. It will set the internal pointer to the last element of the array and return its value.

What does array slice do in PHP?

The array_slice() function returns selected parts of an array. Note: If the array have string keys, the returned array will always preserve the keys (See example 4).

How can I remove a specific item from an array PHP?

In order to remove an element from an array, we can use unset() function which removes the element from an array and then use array_values() function which indexes the array numerically automatically. Function Used: unset(): This function unsets a given variable.


4 Answers

Check out array_slice()

So, if you wanted the first three elements only:

$array = array_slice($array, 0, 3);

If you wanted all but the last three elements:

$array = array_slice($array, 0, -3);

The second parameter is the start point (0 means to start from the begining of the array).

The third parameter is the length of the resulting array. From the documentation:

If length is given and is positive, then the sequence will have that many elements in it. If length is given and is negative then the sequence will stop that many elements from the end of the array. If it is omitted, then the sequence will have everything from offset up until the end of the array.

like image 120
ircmaxell Avatar answered Dec 19 '22 06:12

ircmaxell


Slice it. With a knife.

Actually, with this:

array_slice($array, 0, -3);

Assuming you meant cutting off the last 3 elements.

like image 44
BoltClock Avatar answered Dec 19 '22 06:12

BoltClock


Use array_splice():

$new = array_splice($old, 0, 3);

The above line returns the first three elements of $old.

Important: array_splice() modifies the original array.

like image 40
cletus Avatar answered Dec 19 '22 05:12

cletus


Use array_splice as:

$array = array(0,1,2,3,4,5);
array_splice($array,0,3);
like image 39
codaddict Avatar answered Dec 19 '22 06:12

codaddict