I need to check if two strings (numbers) are the same. However if one of the strings has a leading zero, then all bets are off - it says they are equal:
$hospitalno1 = "64583";
$hospitalno2 = "064583";
if ($hospitalno1 <> $hospitalno2){
echo "Different";
}
How can I compare these two variables as strings rather than as numbers?
Cast them to int
:
$hospitalno1 = "64583";
$hospitalno2 = "064583";
if ((int)$hospitalno1 != (int)$hospitalno2){
echo "Different";
}
yet beware "this string" will become 0
, so add is_int()
prior conversion.
Also instead of <>
you should use !=
despite the fact the former will work in PHP, the latter is cross language standard.
If I understand your question correctly, you don't want the strings to be type juggled.
<> type juggles to match types before comparison,
causing your strings to be ints
!== is a comparitor that doesn't type juggle before comparison
Here's a rundown on comparison operators: http://php.net/manual/en/language.operators.comparison.php
Just use:
<?php
$hospitalno1 = "64583";
$hospitalno2 = "064583";
if ($hospitalno1 !== $hospitalno2){
echo "Different";
}
else
{
echo "same" ;
}
?>
The !==
will do a stringent datatype + value check and will alert if anything is different.
You just have to make use of !==
which will not ignore type otherwise type will be ignored
$hospitalno1 = "64583";
$hospitalno2 = "064583";
if ($hospitalno1 !== $hospitalno2){
echo "Diffrent";
}
You are very close. Just pre-concatenate them with another string character, a
, -
, anything will do
$hospitalno1 = '64583';
$hospitalno1 = 'a-'. $hospitalno1;
$hospitalno2 = '064583';
$hospitalno2 = 'a-'. $hospitalno2;
if ($hospitalno1 <> $hospitalno2){
echo "Different";
}
please try this
<?php
$hospitalno1 = (string)"64583";
$hospitalno2 = (string)"064583";
if ($hospitalno1 !== $hospitalno2){
echo "Different";
}
?>
my php code link >> Code