check if item can be converted to string?

Ok, edited, with incorporating Michiel Pater's suggestion (who's answer is gone now) ans @eisberg's suggestions. settype will return true with objects no matter what, as it seems.

if(
    ( !is_array( $item ) ) &&
    ( ( !is_object( $item ) && settype( $item, 'string' ) !== false ) ||
    ( is_object( $item ) && method_exists( $item, '__toString' ) ) )
)
{
    echo $item;
}

For the sake of completion...

http://www.php.net/is_scalar, available since PHP 4; not a single word about it.. :)


How about

function can_be_string($var) {
    return $var === null || is_scalar($var) || (is_object($var) && method_exists($var, '__toString'));
}

And since PHP 8 you can replace the third condition with $var instanceof Stringable