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 ?
The array_pop() function deletes the last element of 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.
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.
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.
if(empty($transport[count($transport)-1])) { unset($transport[count($transport)-1]); }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With