Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

deleting last array value ? php

Tags:

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 ?

like image 725
Adam Ramadhan Avatar asked Jul 26 '10 19:07

Adam Ramadhan


People also ask

How do you delete the last element of an array in PHP?

The array_pop() function deletes the last element of an array.

How can you remove the last item in an array?

JavaScript Array pop() The pop() method removes (pops) the last element of an array. The pop() method changes the original array. The pop() method returns the removed element.

How do you remove last value?

To remove the last element from an array, call the pop() method on the array, e.g. arr. pop() . The pop method removes the last element from the array and returns it. The method mutates the original array, changing its length.

How do I remove a specific element from an array?

pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array.


2 Answers

if(empty($transport[count($transport)-1])) {     unset($transport[count($transport)-1]); } 
like image 84
Scott Saunders Avatar answered Sep 23 '22 23:09

Scott Saunders


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.

like image 32
Jim Avatar answered Sep 24 '22 23:09

Jim