Php string cast vs strval function which should I use?

They are generally interchangeable because PHP uses automatic type conversion and a variable's type is determined by the context in which the variable is used.

Some differences are that strval($var) will return the string value of $var while (string)$var is explicitly converting the "type" of $var during evaluation.

Also, from the manual for strval():

$var may be any scalar type or an object that implements the __toString method. You cannot use strval() on arrays or on objects that do not implement the __toString method.

As mentioned by @Lars (string) is generally faster.


One is a function call, the other one is an internal typecast. Without having checked, I'd guess the latter one is faster by few cycles, but shouldn't really make a difference.


http://www.php.net/manual/en/language.types.string.php#language.types.string.casting

A value can be converted to a string using the (string) cast or the strval() function.

Looks the same to me.

Tags:

Php

String