douyan0732 2011-04-05 19:59
浏览 113
已采纳

一个Liner将字符串前置或附加到另一个字符串

Not a vital question, just wondering if there is any onliner to do this.

function addString($text, $add, $type = 'prepend') {
   // oneliner here
   return $text;
}

$text = 'World';
addString($text, 'Hello ', 'prepend'); // returns 'Hello World'
addString($text, ' Hello', 'append'); // returns 'World Hello'

Any ideas? : )

  • 写回答

5条回答 默认 最新

  • dprq18175 2011-04-05 20:01
    关注

    What about this, using the ternary ?: operator :

    function addString($text, $add, $type = 'prepend') {
       return $type=='prepend' ? $add . $text : $text . $add;
    }
    


    Note : I actually would probably not use that -- and stay with a classic if/else : not a one-liner, not as nice to read... But probably a lot easier to understand ; and having understandable code is what trully matters.


    Edit after the comment : if you want to make sure that the $type is either 'append' or 'prepend', and still want a one-liner, you could go with something like this :

    function addString($text, $add, $type = 'prepend') {
       return ($type=='prepend' ? $add . $text : ($type=='append' ? $text . $add : ''));
    }
    

    But your code will become harder to read -- and it's probably time to go with something that's longer than just one line of code, and easier to understand.


    For example, why not something like this :

    function addString($text, $add, $type = 'prepend') {
        if ($type === 'prepend') {
            return $add . $text;
        } else if ($type === 'append') {
            return $text . $add;
        } else {
            // Do some kind of error-handling
            // like throwing an exception, for instance
        }
    }
    

    After all, the number of lines has pretty much no impact on the way the code is executed -- and, again, what matters is that your code is easy to understand and maintain.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程