为什么$ var总是返回true?

时间:2016-05-24 08:56:32

标签: php if-statement

我只知道if(var)仅在条件true1工作至今。但是,当我添加变量string之类的内容时,12332之类的其他数字也可以正常工作。这意味着if(var)变量中的工作是true or number or string吗?

<?php
  $Check  = "sosdjf";  echo : true
//$Check  = 12332;     echo : true
//$Check  = false;     echo : false
if($Check){
    echo "true";
}
else{
    echo "false";
}

我们经常检查,例如if($Check == "sosdjf")if condition,但此处if($Check)也是if condition!这就是为什么 ?这是真的吗?

4 个答案:

答案 0 :(得分:1)

让我们来看看你的代码;

您将$check分配给值sosdjf

如果我们对变量执行简单的if($check),因为变量已设置,它将评估为true。这是因为PHP将其转换为boolean,除非符合以下条件,否则true将转换为$check = 'someword'; if ($check === true) { echo 'True'; } else { echo 'False'; } an empty string or the string "0"

你真正应该做的是明确检查

False

上面会输出$check因为boolean不是string,所以它不通过严格类型检查,因为双方不相等。

有关字符串的说明,

  • 任何空的FALSE评估为string
  • 任何非空TRUE 非0 评估为Default project

答案 1 :(得分:0)

返回True当$ Check不为NULL,NOT 0,NOT False,不是“”,不是“0”,未定义(带通知),不是空数组,否则它给你真实

if($Check){
    echo "true";
}
else{
    echo "false";
}

答案 2 :(得分:0)

try this instead - 

in php 
$var = 123; //number
$var1 = "variable"; //string

here $var return true for both variables

if you want to check wether it is a numeric or string do this - 
$check = is_numeric($var); //it will return true

then return your desired output - 
if($check){
  echo "it is a number"; //true
}else{
  echo "it is a not number"; //false
}

答案 3 :(得分:0)

只需添加一些内容,请参阅var_dump(empty(false)); // true var_dump(empty(null)); // true var_dump(empty("")); // true var_dump(empty(0)); // true var_dump(empty("0")); // true 功能:

@WebServlet(name = "Login", urlPatterns = {"/Login"})
public class Login extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
         throws ServletException, IOException { 
     String userId = request.getParameter("userId");    
     String password = request.getParameter("password");
     LoginService loginService = new LoginService();
     boolean result = loginService.authenticate(userId, password);
     Users user = loginService.getUserByUserId(userId);
     if(result == true){
         request.getSession().setAttribute("user", user);       
         response.sendRedirect("deneme.jsp");
     }
     else{
         response.sendRedirect("login.jsp");
     }
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
         throws ServletException, IOException {
     processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
         throws ServletException, IOException {
     processRequest(request, response);
}
@Override
public String getServletInfo() {
     return "Short description";
 }
}