Home > Net >  How to use if-else conditions in the function -php
How to use if-else conditions in the function -php

Time:12-15

I want to define $roomprice in if-else but the result shows nothing. Did I do something wrong?

        $answer = $_POST['ans'];
        $roomprice = roomprice($answer, $roomprice);

        function roomprice($answer, $roomprice)
        {
            if($answer == "singleroom")
            {
                $roomprice = 150;
                return $roomprice;
            }
            else if($answer == "deluxeroom")
            {
                $roomprice = 180;
                return $roomprice;
            }
            
        }

        roomprice($answer, $roomprice);
        echo "$roomprice";

CodePudding user response:

You have to assign the function call to a variable, otherwise the value it returns is lost. E.G.:

$result = roomprice($answer, $roomprice);

CodePudding user response:

You should assign the data returned in the function to a variable.

$roomprice = roomprice($answer, $roomprice);

CodePudding user response:

There is no problem with your function. Only the value of $answer cannot be obtained.

        $answer = 'deluxeroom'; //$_POST['ans'] Cannot be retrieved here.
    $roomprice = roomprice($answer, $roomprice);

    function roomprice($answer, $roomprice)
    {
        if($answer == "singleroom")
        {
            $roomprice = 150;
            return $roomprice;
        }
        else if($answer == "deluxeroom")
        {
            $roomprice = 180;
            return $roomprice;
        }
        
    }

    roomprice($answer, $roomprice);
    echo "$roomprice"; // 180

CodePudding user response:

I see a few issues, although the code should still give you the answer (and also a warning). The one reason you would not be getting the answer would be that $_POST['ans'] is not set properly ( it needs to be set by form post).

you are calling roomprice twice here once on the second line and again on the second last line

you are also trying to pass $roomprice variable to the roomprice function, but the variable is not set (and not needed)

    //$answer = $_POST['ans'];
    //set answer to known value for testing
    $answer = "singleroom";

    //remove $roomprice variable
    //$roomprice = roomprice($answer, $roomprice);
    $roomprice = roomprice($answer);
    
    //echo the $roomprice
    echo "$roomprice";

    //change the function to not need $roomprice
    //function roomprice($answer, $roomprice)
    function roomprice($answer)
    {
        if($answer == "singleroom")
        {
            $roomprice = 150;
            return $roomprice;
        }
        else if($answer == "deluxeroom")
        {
            $roomprice = 180;
            return $roomprice;
        }
        
    }
    //not needed
    //roomprice($answer, $roomprice);
    //echo "$roomprice";
  • Related