dongnong3799 2010-03-16 13:20
浏览 35
已采纳

在PHP中,我可以在函数调用中检查布尔值吗?

I have a function which checks the passed value and returns false or true, if false I want it to add something to an array. The code I've written is below.

if(!check_input($_POST['username'])){
    $errors[] = "Username";
}  

Right now it adds to my array anyway, regardless of what is entered in the form. Is the way I've written that the correct way to check if the return from check_input() is false? I've checked the function's logic by altering the returns to echoes and it's returning the correct value, I'm just not sure if I'm checking it wrong.

I'd previously attempted to write it as $X=check_input etc, and then if(check_value == false) but that doesn't seem to give me the desired result either. Hmmm a quick pointer please!

Edit:

Okay, after looking at my function I think I spotted the problem, I have an if statement, and within that an if else statement, the first if checks the value isn't empty, the second if checks it doesn't exceed its maximum length and returns true/false. I set it to only check the max length if I'd passed that value in - or it's set to nothing. But, on balance I don't have a return true for the main if statement. So my logic is currently, if the value's bigger than nothing then check it against max length, then return true. If I don't check max length and it it does have value it's not returning anything. Hmmm. I'm thinking that's the cause of my issue?

Edit 2:

Thanks all, and to Marvin, who suggested I recheck the function. I've got it working. It's not if something return false, if something else return false, and I took my return true out of the else statement and hey presto!

  • 写回答

2条回答 默认 最新

  • drlma06060 2010-03-16 13:21
    关注

    You need to compare the return value of the function with false using the === operator:

    if(check_input($_POST['username']) === false) {
    

    But if you are sure that the function returns only boolean value your way of doing it should also work.

    Problem comes when, say your function returns false on failure and an integer/string on success. In that case your way of checking will not differentiate between false and 0 (returned as a successful return value)

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

报告相同问题?

悬赏问题

  • ¥15 ansys fluent计算闪退
  • ¥15 有关wireshark抓包的问题
  • ¥15 需要写计算过程,不要写代码,求解答,数据都在图上
  • ¥15 向数据表用newid方式插入GUID问题
  • ¥15 multisim电路设计
  • ¥20 用keil,写代码解决两个问题,用库函数
  • ¥50 ID中开关量采样信号通道、以及程序流程的设计
  • ¥15 U-Mamba/nnunetv2固定随机数种子
  • ¥15 vba使用jmail发送邮件正文里面怎么加图片
  • ¥15 vb6.0如何向数据库中添加自动生成的字段数据。