2

I have written a function that returns data on success and false on failure.

I was wondering if this is considered a proper way of evaluating the return value in php.

function data(){
  if($all_is_good){
    return $data
  }else{
    return false;
  }
}

$data = data(); //basically either a long series of strings or arrays

if(!$data){  //<-- this is the line I'm concerned about, is it safe to assume this?
   echo 'oh no, bad stuff happened';
}

Thank you so much!

3 Answers 3

4

What you have there is fine, although alternatively, you could use if($data === false) {. This ensures that $data is actually false, considering 0 and NULL are also seen as false.

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

1 Comment

An empty string "" also evaluates to false.
3

It depends in what exactly $data is (both its type and its value). It makes sense both to leave it as-is (if the type of the value in $data is not certain) or make the check explicit (e.g. $data == false or empty($data)) if it's a known type. It's really dependent on the specific circumstances.

See Converting to boolean.

Comments

1

It is safe unless there is a valid value for $data that would evaluate to false. A long (i.e. nonempty) series of strings or arrays won't evaluate to false, but still it's a potential pitfall.

You might consider using a strict comparison: if(data===False)

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.