简体   繁体   English

一行if-else

[英]one line if-else

An easy question for you guys. 你们一个简单的问题。
I assume there must be an easier (= less code) way to do the following snippet: 我假设必须有一种更简单(=更少的代码)的方式来执行以下代码片段:

if (link_validate_url($items[0]['url_value'])) {
} else {
    form_set_error('', 'Not a valid URL.');
}

Simply negate the return value using the ! 只需使用!取反返回值即可! operator: 操作员:

if (!link_validate_url($items[0]['url_value'])) {
    form_set_error('', 'Not a valid URL.');
}

Of course you could shorten it even more, but IMO that reduces the readability: 当然,您可以进一步缩短它,但是IMO会降低可读性:

if (!link_validate_url($items[0]['url_value']))
    form_set_error('', 'Not a valid URL.');

or even 甚至

if (!link_validate_url($items[0]['url_value'])) form_set_error('', 'Not a valid URL.');

Try this: 尝试这个:

if (! link_validate_url($items[0]['url_value'])) {
    form_set_error('', 'Not a valid URL.');
}

Also, you might want to read this . 另外,您可能需要阅读this

You could (ab)use the ternary operator. 您可以(ab)使用三元运算符。

Typically it is condition ? action if true : action if false; 通常是condition ? action if true : action if false; condition ? action if true : action if false; But you can leave actions blank. 但是您可以将操作留空。

This leaves you with: 这使您拥有:

link_validate_url($items[0]['url_value'] ?: form_set_error('', 'Not a valid URL.');

Edit: 编辑:

This is PHP 5.3+ 这是PHP 5.3+

Notes on this operator can be found here 有关此运算符的注释,请参见此处

if (!link_validate_url($items[0]['url_value'])) {
   form_set_error('', 'Not a valid URL.');
}

or you can (ab)use common compiler optimization that the second part of an or is never executed if the first part is true 或者您可以(ab)使用常见的编译器优化,如果第一个部分为true,则或的第二部分永远不会执行

link_validate_url($items[0]['url_value']) or form_set_error('', 'Not a valid URL.');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM