Vihanga Mohottige
Vihanga Mohottige

Reputation: 23

PHP elseif not working.(Compare operators with integers)

function ageIssue($age){
    if ($age > 10) {
        echo "Age is greater than 10";
    } elseif ($age>20) {
        echo "Age is greater than 20";
    } elseif($age>30) {
        echo "Age is greater than 30";
    }else {
        echo "Enter valid age";
    }
 }

 ageIssue(32);

What is the fault of this code? I need the answer "Age is greater than 30" but But always it says "Age is greater than 10". Help please....

Upvotes: 2

Views: 158

Answers (4)

Fredrick Wampamba
Fredrick Wampamba

Reputation: 11

You need to start from the largest as you check the age

    function ageIssue($age)
{
    if ($age > 70) {
        return "Age is greater than 70";
    } elseif ($age > 50) {
        return "Age is greater than 50 but less than 70";
    } elseif ($age > 30) {
        return "Age is greater than 30 but less than 50";
    } elseif ($age > 10) {
        return "Age is greater than 10 but less than 30.";
    } elseif ($age >= 1) {
        return "Age is between 1 and 10.";
    } else {
        return "Invalid Age enter";
    }
}

echo ageIssue(32);

Upvotes: 1

Kenneth Korir
Kenneth Korir

Reputation: 51

You can start by testing value from largest to smallest if statements by

  1. Calling a returning method
function ageIssue($age){
    if ($age > 70) {
        return "Age is greater than 70";
    } if ($age>50) {
        return "Age is greater than 50 but less than 70";
    } if($age>30) {
        return "Age is greater than 30 but less than 50";
    }if($age>10){
        return "Age is greater than 10 but less than 30.";
    }
    if($age>=1){
      return "Age is between 1 and 10.";
    } else {
        return "Invalid Age enter";
    } 
} 

echo ageIssue(32);

Upvotes: 3

Piper2
Piper2

Reputation: 299

Your code executes up to the first true evaluation... break up your if statements to simplify your checks ... notice that I start with the least age.

Like below:


function ageIssue($age){

    $output = "Enter valid age";


    if ($age > 10) {
        $output = "Age is greater than 10";
    }

    if ($age > 20) {
        $output = "Age is greater than 20";
    } 

    if($age > 30) {
        $output = "Age is greater than 30";
    }

    echo $output;

 }

 ageIssue(32);

Upvotes: 3

ttrasn
ttrasn

Reputation: 4826

Your code logic is wrong. If you want to handle with if else, you must do it like this:

function ageIssue($age){
    if ($age > 30 && $age < 40) {
        echo "Age is greater than 30";
    } elseif ($age>20) {
        echo "Age is greater than 20";
    } elseif($age>10) {
        echo "Age is greater than 10";
    }else {
        echo "Enter valid age";
    }
}

Upvotes: 5

Related Questions