php:写这个的快捷方式?
写这个的最短方法是什么?
if(strpos($haystack, $needle)!==false){
$len = strpos($haystack, $needle)+strlen($needle);
}else{
$len = 0;
}
我记得我在某处看到了一些快捷方式,可以同时检查和设置变量。
what would be the shortest way to write this?
if(strpos($haystack, $needle)!==false){
$len = strpos($haystack, $needle)+strlen($needle);
}else{
$len = 0;
}
I remember that I saw some shortcut somewhere for this that checked and set a variable at the same time.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我建议不要使用三元
?:
运算符,即使它更短。I'd recommend against the ternary
?:
operator, even if it is shorter.而且,在我看来,三元运算符对可读性影响很大。
and, in my opinion, ternary operator is terrible impact on readability.
它被称为 十元运算符,可以像这样使用:
不过,您应该小心使用它,因为它会使某些表达式变得难以阅读。
It is called the tenary operator and can be used like this:
You should use it with care though, because it can make some expressions quite hard to read.
另请参阅三元运算。
See also Ternary Operation.
一种不同的方法:
可能更慢并且更占用内存,但它确实需要更少的打字。所以它是否实际上是一个快捷方式取决于定义。如果您对三元运算符和求值条件下的赋值过敏,它确实提供了一个有效的选项。
您也可以这样做,
尽管使用 preg_ 函数来搜索固定字符串再次有点浪费资源。
A different approach:
Probably slower and more memory-intensive, but it does require less typing. So whether or not it's actually a shortcut depends on the definition. It does present a valid option if you're allergic to ternary operators and assignment within evaluation conditions.
You could also do
although again it's a bit wasteful of resources to be using preg_ functions to search for fixed strings.