# PHP string cast vs strval function, which one should I use?

PHPServer Side ProgrammingProgramming

A value can be converted into a string with the help of (string) cast or the strval() function.

The strval() function is a function call whereas (string) cast is an internal type casting method.

Unless there is some specific dataset or use case, both of these can be used interchangeably.

This is because PHP uses automatic type conversion, due to which a variable's type is determined based on the context in which it is used.

The strval($var) function returns the string value of$var whereas the (string)$var explicitly converts the "type" of$var during the process of evaluation.

The \$var can be any scalar type or an object that implements the __toString method.

The strval() can't be used on arrays or on objects that do not implement this __toString method.

In general, (string)cast is relatively quicker.

Published on 06-Apr-2020 08:55:30