...

View Full Version : IF statment not working correctly



tomharto
08-26-2011, 07:18 PM
This is probably a simple issue but i cant seem to figure out why.



if (count($_POST) !== "10")
{
echo "An error occured (001)<br />";
echo count($_POST);
}


That always echoes An error occured etc, but the count($_POST) echoes 10.

Anyone see my problem?

Inigoesdr
08-26-2011, 07:25 PM
You are doing a strict type comparison (http://php.net/language.operators.comparison) of an integer against a string. It will never be true. You should use one of these instead:

if (count($_POST) !== 10)
{
echo "An error occured (001)<br />";
echo count($_POST);
}

// or

if (count($_POST) != 10) // you can use a string for 10, but it doesn't make sense if you are specifying it in code
{
echo "An error occured (001)<br />";
echo count($_POST);
}

oracleguy
08-26-2011, 07:27 PM
It isn't working because you are comparing an integer to a string and you using the !== comparison operator which means "a and b are not equal or not the same type".

Change it to:

if (count($_POST) !== 10)

Is there a reason you used '!==' instead of '!=' in your if statement? In any event you shouldn't write the number as a string since PHP would have to do a type conversion.

tomharto
08-26-2011, 07:32 PM
Theres no reason i used !==. So your saying it would be better using this?


if (count($_POST) !== "10")

Inigoesdr
08-26-2011, 07:35 PM
Theres no reason i used !==. So your saying it would be better using this?


if (count($_POST) !== "10")

No... it would be better using this:

if (count($_POST) !== 10)

tomharto
08-26-2011, 08:01 PM
Okay, thanks :)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum