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
Array.prototype.pop() by JavaScript convention.
let fruit = ['apple', 'orange', 'banana', 'tomato'];
let popped = fruit.pop();
console.log(popped); // "tomato"
console.log(fruit); // ["apple", "orange", "banana"]
Use splice(startPosition, deleteCount)
array.splice(-1)
var array = ['abc','def','ghi','123'];
var removed = array.splice(-1); //last item
console.log( 'array:', array );
console.log( 'removed:', removed );
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).
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);
Use array_splice and specify the number of elements which you want to remove.
Copy$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_splice($stack, -2);
print_r($stack);
Output
Array
Copy(
[0] => orange
[1] => banana
)
You can use array_slice() with a negative length:
Copyfunction array_remove($array, $n) {
return array_slice($array, 0, -$n);
}
Test:
Copyprint_r( array_remove($stack, 2) );
Output:
CopyArray
(
[0] => orange
[1] => banana
)