6

I am looking for the correct way to handle a return statement with a bool/string. For example I do all my checking inside the function and return true if it all passes. However if something went wrong I would like to return a string of what went wrong rather than just return false; with a general string. Does php assume false if a var is set to anything besides true? What is the correct way to handle this? Here's an example of what I'm doing

<?php
$a = 2;

$result = CheckVar($a);
if ($result)
{
    echo 'Correct!';
}
else
{
    echo $result;
}

function CheckVar($var)
{
    if ($var == 1)
    {
        return true;
    }
    else
    {
        return 'This is not the correct answer. You supplied '.$var;
    }
}
?>

It seems this method works, however is this good programming etiquette? Or is there another way I should be doing this? Thank you for your time.

5
  • 1
    You need to understand falsy values in PHP (Javascript, also). stackoverflow.com/questions/699507/… Commented Oct 10, 2011 at 4:45
  • 1
    @zzzzBov Exceptions are expensive. Don't throw an exception unless you have a very good reason to. Commented Oct 10, 2011 at 4:46
  • @NullUserExceptionఠ_ఠ, don't optimize prematurely. Yes, using many exceptions can be expensive. Commented Oct 10, 2011 at 4:48
  • 2
    @zzzzBov Using exceptions also uglifies your code. IMO it makes no sense to throw an exception if "the answer is not correct." Exceptions should be used to handle code that doesn't behave the way it's supposed to - thus the name "Exception." You fully expect the answer to be incorrect. Commented Oct 10, 2011 at 4:53
  • 1
    And I would know it. After all, I am an Exception :) Commented Oct 10, 2011 at 4:58

4 Answers 4

14

Does php assume false if a var is set to anything besides true?

Not at all. PHP will return whatever the variable was set to. And actually since you have a non-empty string, that's a "truthy" value (ie: true in a boolean context). Since you used if ($result) as your check and you return a "truthy" value, the condition is always true. You need to change that check to:

if ($result === true) {
    ...

What is the correct way to handle this?

I think it's a good enough way to handle it. An alternative would be to pass an error string variable by reference, and have the fail part of your code fill that, eg:

function check($var, &$error) {
    if ($var == 1) {
        return true;
    } else {
        $error = 'This is not the correct answer. You supplied ' . $var;
        return false;
    }
}

Some native PHP functions behave like this (eg: exec().) Yet another alternative is to return an array with the errors, like Jared suggested. I personally use this option when I expect multiple errors (eg: a form validation routine):

function check_stuff($stuff) {
    $errors = array();
    if (!$condition1) {
        $errors[] = 'Condition 1 failed';
    }

    if (!$condition2) {
        $errors[] = 'Condition 2 failed';
    }

    return $errors;
}

Now you can also take advantage of the fact that empty arrays are falsy:

$errors = check_stuff($your_stuff);
if (!$errors) {
    echo 'No errors!';
} else {
    print_r($errors);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Although I have approached this in different ways over the year's, in this case I might want to return an array of errors from the function, and then test the return result for how many array member's it has. This way, I don't have to maintain two different contexts (the argument and the return value).
@Jared I also use arrays when I anticipate multiple errors (eg: a form validator).
6

You can use === to check if the returned value is boolean true. === checks the type as well the value.

if ($result === true)
{
    echo 'Correct!';
}
else
{
    echo $result;
}

1 Comment

This works well, though it seems pass-by-reference variables are better practicing standards. Thank you for your help.
1

I came up against this recently, my function would either return an error message as a string or return true like this:

function check_something(){
    if(condition){
        return 'error message';
    }
    // if we got this far all is good!
    return true;
}

I would call it and check the outcome like this:

$var = check_something();

if($var !== true){
    // $var is not boolean true, so it must be a string
    echo $var;
}

This checks that the outcome of the function is not just a truthy string, but is explicitly a boolean true

1 Comment

after coming back to this years later, it's a bad idea to have a method return a mixed type. there may be times when it's ok but as a rule you should always return only one type from a method, and throw exceptions for errors. This makes your whole stack a lot cleaner and easier to reason about.
0

This could be useful to someone returning true or returning false as a string.

if (is_bool($result)) 
{
   echo 'Result is a true bool';
} 
else
{
   echo $result.'returning a string';
}

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.