I'm somewhat confused and was hoping you guys could help. I'm writing something simple that takes a value from the posted name field and returns it, checking to see beforehand that its a string(correct) or an integer(in which case it'll say 'a name is not a number').
<?php
$number = array("1","2","3","4","5","6","7","8","9","0");
if(!isset($_POST['submit'])){
?>
<p>Enter your name</p>
<form method="post" action="action4.php">
<input type="text" name="name">
<input type="submit" name="submit">
</form>
<?php
}else{
$name = $_POST['name'];
foreach($number as $v){
$int = (int)$v;
}
if($name == $int){
print "This is a number and not a name.";
}else{
print $name;
}
}
?>
Given that every number entered into the name field was seen as a string, I cycled through the array and converted every digit to an integer. When entering an integer into the name field however, rather than getting "this is a number and not a name" I get $name. Reciprocally if I enter in a string, I get "this is a number and not a name."
var_dumping both name and int in the if statement returns as expected: $name as string and $int as integer. So why are they comparing as true?
Because you are doing nothing but assigning a variable in your foreach
loop the final value of $v
is 0
. When PHP compares strings to integers it converts the string to an integer to do the comparison (see Type Juggling). So $name
becomes 0
. 0
equals 0
so your if statement is always true.
To overcome this you need to compare variable type and value (and do your comparison inside your foreach
loop). This means using the ===
comparison operator which compares both type and value as opposed to just value which is what ==
does.
Reference: Comparison operators, Type juggling
You have to use ===
to compare the types and values of variables. If you use ==
php will automatically convert both values before comparing them.
But to check that the inputs aren't integers, it should be enough to test with is_numeric
.