0

I've got a simple function to conditionally convert units into feet or inches for display. I'd also like to use it to conditionally add the actual text ft or in to the end. I can't just add that text in every case, because I'd end up with 36 in x 24 in x 10 in when what you want is 36x24x10 in.

So basically I'm trying to do this:

function ex($x, $y) {
    if only $x is specified {
        if ($x < 50) {
            return $x/25.4
        }
        else {
            return $x/304.8
        }
    }
    elseif $x and $y are both specified {
        if ($x < 50) {
            return ' in';
        }
        else {
            return ' ft';
        }
    }
}

echo ex($NumberToConvert).'x'.ex($OtherNumberToConvert).example($NumberIWantToConvert,1);

But of course that results in "missing argument 2" warnings. The obvious hack is to use if ($y > 0) and always have to specify two arguments (making the latter 0 when I'm looking for numerical output and 1 when I'm looking for text). But is there something more elegant?

(yes I know this only makes sense if both numbers are <50 or neither are)

1
  • function ex($x, $y='') { Commented Jan 15, 2017 at 1:54

1 Answer 1

1

Make use of default argument values of a funciton. So your ex function should be like this:

function ex($x = null, $y = null) {
    if($x != null && $y == null){
        if ($x < 50) {
            return $x/25.4
        }else{
            return $x/304.8
        }
    }elseif($x != null && $y != null){
        if ($x < 50) {
            return ' in';
        }else{
            return ' ft';
        }
    }
}

Take the default argument as null for both $x and $y in the function, and process these variables inside the function accordingly.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.