这些PHP条件是相同的还是有优势? [英] Are these PHP conditionals the same or does one have an advantage

查看:64
本文介绍了这些PHP条件是相同的还是有优势?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编写这样的PHP条件是否有任何优势:

Is there any advantage to writing a PHP conditional like this:

if ($variable != NULL) {

if (!empty($variable)) {

versus

if ($variable) {

它们不是一模一样的吗?如果您只是想知道变量是否存在,则似乎最后一个总是最简单的。感谢您帮助我了解此处的区别。我错过了PHP 101的第一天。

Aren't they all same thing? It seems like the last is always the simplest if you are just trying to tell whether the variable exists or not. Thanks for helping me understand the difference here. I missed the first day of PHP 101.

推荐答案

我同意Sean的观点,但我将用简单的英语概述它们的作用:

I agree with Sean but I'll outline what each does in plain English:

if ($variable != NULL) {

$ variable 如果未设置,将为 NULL 。这实际上与 isset 相同,并且与未定义的变量相同。

$variable will be NULL if it hasn't been set. This is practically the same as isset and the same as the variable being undefined.

if (!empty($variable)) {

通常,这会检查 $ variable 作为字符串((字符串)$ variable )具有 strlen of0。但是 true 将使其返回 false ,不为0的整数和空数组也将返回。出于某些原因(我认为这是错误的), $ variable ='0'; 将返回 true

Generally, this checks whether $variable as a string ((string) $variable) has a strlen of 0. However true will make it return false, as will integers that aren't 0 and empty arrays. For some reason (which I believe to be wrong) $variable = '0'; will return true.

if ($variable) {

此true / false检查的行为类似于(boolean)$ variable -基本上,该变量在转换为布尔值后是否返回true。

This true/false check acts like (boolean) $variable - basically whether the variable returns true when converted to a boolean.

一种思考方式是,除了返回相反的值外,它的行为与空相同。

One way to think about it is that it acts the same as empty, except returns the opposite value.

有关(布尔值)$ variable (类型转换/变戏法)的含义的更多信息,请参见此手册页

For more information on what I mean by (boolean) $variable (type casting/juggling) see this manual page.

(PHP开发人员:主要是记忆,如果我错了,请纠正我!)

(PHP devs: this is mainly by memory, if I'm wrong here please correct me!)

这篇关于这些PHP条件是相同的还是有优势?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆