Adam Ramadhan
Adam Ramadhan

Reputation: 22810

deleting last array value ? php

1 question type

$transport = array('foot', 'bike', 'car', 'plane');

can i delete the plane ? is there a way ?

2 question type

 $transport = array('', 'bike', 'car', ''); // delate the last line
 $transport = array('', 'bike', 'car', 'ferrari'); // dont the last line
 $transport = array('ship', 'bike', 'car', 'ferrari'); // dont the last line

is there a easy way to delete the last array " if last array value is empty then delete " if not empty then don't delete ? but not to delete the first array ?

Upvotes: 26

Views: 82780

Answers (5)

Martin AJ
Martin AJ

Reputation: 6697

You can simply do that by array_pop() function:

array_pop($transport);

Upvotes: 14

viji
viji

Reputation: 313

$endvalue = & end($transport);
array_pop($endvalue);

Upvotes: 3

Scott Saunders
Scott Saunders

Reputation: 30394

if(empty($transport[count($transport)-1])) {
    unset($transport[count($transport)-1]);
}

Upvotes: 48

JAL
JAL

Reputation: 21563

for # 1,

$transport=array_slice($transport,0,count($transport)-1)

Upvotes: 17

Jim
Jim

Reputation: 18853

The easiest way: array_pop() which will pop an element of the end of the array.

As for the 2nd question:

if (end($transport) == "") { 
    array_pop($transport); 
}

Should handle the second.

EDIT:

Modified the code to conform to the updated information. This should work with associative or indexed based arrays.

Fixed the array_pop, given Scott's comment. Thanks for catching that!

Fixed the fatal error, I guess empty cannot be used with end like I had it. The above code will no longer catch null / false if that is needed you can assign a variable from the end function and test that like so:

$end_item = end($transport);
if (empty($end_item)) { 
    array_pop($transport); 
}

Sorry for posting incorrect code. The above I tested.

Upvotes: 35

Related Questions