3

I have a method return type can either be an array of things or false.

I am therefore casting the result to an array to try to ensure my code doesnt need to check for false or array.

But, php is casting false to an array containing 1 element: false:

array(1) {
  [0]=>
  bool(false)
}

WHY!

Is there a way to achieve this without the if statement?

i.e.

if ($returnValue === false) {
    return array();
} else {
    return $returnValue;
}
3
  • 1
    "the if statement. What if statement? Commented Nov 11, 2013 at 17:04
  • How are you doing the casting? Commented Nov 11, 2013 at 17:05
  • the casting is like (array)$returnValue Commented Nov 11, 2013 at 17:05

1 Answer 1

6

Working as designed. The manual specifies :

For any of the types: integer, float, string, boolean and resource, converting a value to an array results in an array with a single element with index zero and the value of the scalar which was converted. In other words, (array)$scalarValue is exactly the same as array($scalarValue).

Can't you simply use a ternary operator?

return (is_array($returnValue) ? $returnValue : array());
Sign up to request clarification or add additional context in comments.

2 Comments

+1 it should always be like that, whenever you expect an array as the return type.
Indeed. You might have an array of Booleans. Also worth noting that casting null to an array gives an empty array, not null, but which will evaluate to false in a loose conditional (with == rather than ===, or without a comparison operator).

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.