Strange failure of Php - makes NO sense!

Greetings,

Why in Gods name is this condition firing?
That is I have this Php code:

if (!isset($_POST['country']) OR ($_POST['country'] == 0)) {
		$error = 'You have not indicated what Country you are from.<p>Country: ' . $_POST['country'];
	}

But $_POST[‘country’] is set! That is when I do:
echo $error, it produces:

You have not indicated what Country you are from.
Country: Canada

Thank you for this insight, since I am totally stupmed by WHY in GODs name this condition is firing where as you can see $_POST[‘country’] is set!

It’s the == 0 condition that’s firing. the integer value of a string that does not start with digits is 0.

What StarLion said. You want to use null.

I dont get it!
How is it that a String is equaling ZERO (0)???

FYI, I changed the test to be:

if (!isset($_POST[‘country’]) OR ($_POST[‘country’] == ‘’)) {
$error = 'You have not indicated what Country you are from.<p>Country: ’ . $_POST[‘country’];
}

and it works Ok now.
But I do not get it how in GODs name a string, for example ‘Canada’, is equaling 0?
Or did the basic of Computer Science completely change and I missed that :slight_smile:

PHP tries to convert your string into a number, so when comparing strings it’s just to check if the string is empty or equal to null. I also find it weird how PHP equates values of converting to bool for that matter.

It’s not that difficult to wrap your head around?

String: “12534Somethinng”
INT value 12534.

String “Something”
INT value 0.

String “Some9342342”
INT value 0.

You could also have Type-specific comparisoned (===), which would return false because String != int.

http://www.php.net/manual/en/language.types.string.php#language.types.string.conversion

…because when you compare “Canada” to an integer, PHP casts “Canada” into an Integer for comparison. When it does this, it converts it into a 0.



<?php
error_reporting(-1);
ini_set('display_errors', true);

var_dump(
  (int)'Canada'
);

# int(0)


See Type-Juggling in the manual.

Well personally I think this is a design flaw in Php.
I mean why in Gods name should string ‘Canada’ equal 0!
But it is the way it is.
So thanks your intel anyway on this matter.

Its called being a dynamic programming language. If you cannot be bothered to understand that, and call it a flaw then I suggest you forget PHP and move on to a strict typed language.

You could try empty instead of isset

if (empty($_POST['country'])) {
        $error = 'You have not indicated what Country you are from.<p>Country: ' . $_POST['country'];
}

From manual:
The following things are considered to be empty:

“” (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
“0” (0 as a string)
NULL
FALSE
array() (an empty array)
var $var; (a variable declared, but without a value in a class)

Well I could have thought of a nicer way of saying the same thing
Good day anyway :slight_smile:

What should it equal?