duankuaizhe8257 2011-12-29 02:11
浏览 28
已采纳

如何“rtrim”PHP数组(仅向数组的END移除空元素)并尽可能避免使用for或类似的循环

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:

  1. There can be a series of single or consecutive empty elements before the last non-empty element in the array.
  2. No need to worry about an empty array, but if this case is covered it's totally fine.

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"
)
  • 写回答

4条回答 默认 最新

  • douyi1944 2011-12-29 02:19
    关注

    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:

    • Get an array with all values that are not in array(""). Keys will be preserved (that's the important part, the keys in your array are 0-n).
    • Get the key of the last element.
    • Slice the array from start to that position.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?