if(empty($transport[count($transport)-1])) {
unset($transport[count($transport)-1]);
}
Answer from Scott Saunders on Stack Overflowif(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.
Videos
Using array_slice is simplest
$newarray = array_slice($array, 1, -1);
If the input array has less than 3 elements in it, the output array will be empty.
To remove the first element, use array_shift, to remove last element, use array_pop:
<?php
$array = array('10', '20', '30.30', '40', '50');
array_shift($array);
array_pop($array);
array_shift($end); //removes first
array_pop($end); //removes last
Use explode instead of preg_split. It is faster.
Then you can use array_pop and array_shift to remove an item from the end and beginning of the array. Then, use implode to put the remaining items back together again.
A better solution would be to use str_pos to find the first and last _ and use substr to copy the part inbetween. This will cause only one sting copy, instead of having to transform a string to array, modify that, and put the array together into a string. (Or don't you need to put them together? The 'I need 'os_disk' at the end confuses me).