nickyb
nickyb

Reputation: 325

Simple PHP If Statement Not Acting As Expected

This is a simple year validation that should check if the year is between 1900 and the current year. If the year is valid it should be displayed as the input's value.

    if(!empty($year) && $year >= 1900 || !empty($year) && $year <= date('Y')){
 $yearHolder = 'value="'.$year.'"';
}else{
$yearHolder = 'placeholder="Year"';
}

The problem I'm having is that the statement does not work, and passes any numbers through.

Upvotes: 0

Views: 68

Answers (5)

Mark B
Mark B

Reputation: 682

Try:

if(!empty($year) && $year >= 1900 && $year <= date('Y')){

No need to check if $year is empty twice and make them all ANDs.

Upvotes: 0

Olaitan Mayowa
Olaitan Mayowa

Reputation: 713

You can try this.

if(!empty($year) && $year >= 1900 && $year <= date('Y')){
    $yearHolder = 'value="'.$year.'"';
}else{
    $yearHolder = 'placeholder="Year"';
}

Upvotes: 1

user3602271
user3602271

Reputation: 1

Consolidating other suggestions, you could try something like this:

if (!empty($year) && $year >= 1900 && $year <= date('Y')) {
    $yearHolder = 'value="' . $year . '"';
} else {
    $yearHolder = 'placeholder="Year"';
}

This removes the redundant check for empty values, corrects your || to an &&

Upvotes: 0

Rizier123
Rizier123

Reputation: 59701

You have to change your middle || OR condition to and AND condition, to get your logic, which you want. Right now in other words your condition is:

IF $year is NOT empty AND $year is either bigger than 1900 OR less than 2015

But what you want is:

IF $year is NOT empty AND $year is either bigger than 1900 AND less than 2015

So your if statement should look something like this:

if(!empty($year) && $year >= 1900 && $year <= date("Y"))

Also note, that the function call date() is at the end, which makes it only execute, if the other two pieces in the condition are TRUE. That is because PHP has short circuit evaluation.

Upvotes: 0

Kirs Sudh
Kirs Sudh

Reputation: 298

To be sure about conditions, place it separately.

if(!empty($year))
{
    if ($year >= 1900 && $year <= date('Y'))
    {
        $yearHolder = 'value="'.$year.'"';
    }else{
        $yearHolder = 'placeholder="Year"';
    }
} else {
    echo "Year is empty";
}

Upvotes: 0

Related Questions