Daniel Hyuuga
Daniel Hyuuga

Reputation: 466

PHP - Grabbing items of an array except for last index

I was wondering if there is any way to grab all items in array except for last index, like in Python you can do

>>> a = [1,2,3,4,5]
>>> a[:-1]
[1,2,3,4]

I tried array_slice($a, -1) and it doesn't work, also best if it can be done without knowing an array's length.

Upvotes: 0

Views: 143

Answers (5)

SPokhariyal
SPokhariyal

Reputation: 11

Array Slice is function, you can use

$k = array( "India", "UK", "USA" );

$sliced = array_slice($k, 0, -1); 

print_r($sliced);

Output:

Array
(
    [0] => India
    [1] => UK
)

Upvotes: 1

Ronser
Ronser

Reputation: 1875

Try array_pop or array_slice

array_slice($a, 0, -1);
print_r($a);
  // or
$arr = array_pop($a);
print_r($a);

for array_slice the params are

array array_slice ( array $array , int $offset [, int $length = NULL [, bool $preserve_keys = false ]] )

in your code you have set the start(offset) as -1 thats why it didn't work

array_slice($a, 0, -1); here $a is the array 0 the offset or starting point -1 the length

Upvotes: 1

Cyclonecode
Cyclonecode

Reputation: 30051

You just have to specify an offset and an negative length for this to work:

$array = array(1, 2, 3, 4, 5);
$array = array_slice($array, 0, -1);
print_r($array);
// will display Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 ) 

Of course you could also use array_pop() to remove the last element from the array:

array_pop($array);
print_r($array);
// will display Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 ) 

Reference
array_slice()
array_pop()

Upvotes: 1

Ram Sharma
Ram Sharma

Reputation: 8819

try array_pop() or array_slice

array_pop($array);

or

array_slice($array, 0, -1);

Upvotes: 1

Tibor B.
Tibor B.

Reputation: 1690

Use array_pop:

$array = array(1, 2, 3, 4, 5);
$last = array_pop($array);
print_r($array);

Outputs:

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

PHPFiddle Link: http://phpfiddle.org/main/code/i02x-w9m6

Upvotes: 2

Related Questions