tags:

views:

60

answers:

3

Hi all

Following code:

<?php
$str = "19.09.02";
if(substr($str, -3, 2) == ".0")
{
    // Doing something
}

$str2 = "19.09.2002";
if(substr($str2, -3, 2) == ".0")
{
    // Doing something
}
?>

Why does the second statement apply (without regexp)? and how can I solve, that it just apply the first expression?

Thank you

+6  A: 

I think you should use the identity (===) operator to fix this :)

One of the main differences of === vs == is that === doesn't cast at all, it is a very strict comparison.

Dennis Haarbrink
Ouh, very nice, thanks a lot :-)
Xarem
A: 

Just write === instead of ==

you could also use something like:

if(preg_match("!([0-9]{2}).([0-9]{2}).([0-9]{2,4})!", $str, $found)){
    list($day, $month, $year) = array_shift($found);

    if(strlen($year)==4){
        //must be 4
    }else{
        //must be 2...
    }
}
wodka
A: 

Try === operator. The problem is that in both the cases the value returned is 0 and it is being compared with another 0.

Shubham