Much like rtrim() to a string, how do I remove the empty elements of an array only after the last non-empty element towards the end of the array while avoiding a for or similar loop and possibly using PHP's array functions instead?
I'm actually looking for the fastest/most efficient/elegant way, but if this is not possible without a for or similar loop or I'm mistaken about "fast/efficient/elegant" especially with PHP's array functions then I'd be more than happy to learn/know what's best. Thanks.
Other assumptions:
For example:
Array
(
    [0] => ""
    [1] => "text"
    [2] => "text"
    [3] => ""
    [4] => "text"
    [5] => ""
    [6] => ""
    [7] => "text"
    [8] => ""
    [9] => ""
)
would end up being:
Array
(
    [0] => ""
    [1] => "text"
    [2] => "text"
    [3] => ""
    [4] => "text"
    [5] => ""
    [6] => ""
    [7] => "text"
)
and
Array
(
    [0] => "text"
    [1] => "text"
    [2] => "text"
    [3] => "text"
    [4] => "text"
    [5] => "text"
    [6] => "text"
    [7] => ""
    [8] => ""
    [9] => ""
)
would end up being:
Array
(
    [0] => "text"
    [1] => "text"
    [2] => "text"
    [3] => "text"
    [4] => "text"
    [5] => "text"
    [6] => "text"
)
                In order to remove empty elements from an array, filter() method is used. This method will return a new array with the elements that pass the condition of the callback function.
The array_pop() function deletes the last element of an array.
function trimArray(&$value) { $value = trim($value); } $pmcArray = array('php ','mysql ', ' code '); array_walk($pmcArray, 'trimArray'); by using array_walk function, we can remove space from array elements and elements return the result in same array.
It's like you wrote it in your question: As long as the last value is an empty string, remove it from the array:
while ("" === end($array))
{
    array_pop($array);
}
Edit: I have no clue how serious this is, however for the fun, I've come up with this which does not uses any loop in user-code, however, loops are involved for sure inside PHP C functions. Probably this can make a difference, no idea, to enjoy responsively:
$array = array_slice($array, 0, key(array_reverse(array_diff($array, array("")), 1))+1);
How it works:
array(""). Keys will be preserved (that's the important part, the keys in your array are 0-n).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