38

What is the difference between doing a (string) cast and strval() in PHP? Which should I use?

  1. (string)$value
  2. strval($value)
1
  • I was hoping that strval($value) would magically 'convert' a binary string into something that fits in the default (UTF-8) encoding of PHP. Then I realised all of the native string functions are actually byte functions. There is no advantage in using strval() over (string). Commented Jul 3, 2018 at 9:35

6 Answers 6

31

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

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

Looks the same to me.

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

Comments

11

Community warning: this answer is factually incorrect. (string)$var does not explicitly convert the "type" of $var during evaluation but returns the the string value of $var all the same. Neither of these expressions are "faster", being essentially the same.

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.

6 Comments

"$var is actually changing the "type" of $var.": Thats wrong, because as long as you don't assign something to the variable nothing will change it. "You cannot use strval() on arrays or on objects that do not implement the __toString method." Thats right, but that also applies to the (string)-cast. Thus no different here.
I stand corrected. I have adjusted my answer to be more accurate. The documentation on the boolean type page uses the phrase "explicitly convert" so I took that to mean that the type of $var was being changed but a call to settype() is required for that.
could you provide a link to the manual you are talking about?
The quote "To explicitly convert a value to boolean, use the (bool) or (boolean) casts." comes from the "Booleans" page... us3.php.net/manual/en/… just under the "Converting to boolean" section header.
I would argue that casts are generally more preferred as canonical "modern" PHP. They may have small perf differences, but casting is also a technique used in numerous other languages. The trend in PHP has been moving from small C like functions to language features (destructuring, casting, null coalescing, etc) for common data operations. I think this follows a similar trend in other communities, too.
|
9

I'm not sure how this applies to various versions of PHP, but when looking at the generated opcodes, both variants generate the same opcodes, and thus perform exactly the same.

Input:

<?php
function s1(int $val) {
    return (string)$val;
}
function s2(int $val) {
    return strval($val);
}

Output as generated by https://3v4l.org/3gFWj/vld#output

Function s1:
Finding entry points
Branch analysis from position: 0
1 jumps found. (Code = 62) Position 1 = -2
filename:       /in/3gFWj
function name:  s1
number of ops:  4
compiled vars:  !0 = $val
line     #* E I O op                           fetch          ext  return  operands
-------------------------------------------------------------------------------------
   2     0  E >   RECV                                             !0      
   3     1        MAKE_REF                                         ~1      !0
         2      > RETURN                                                   ~1
   4     3*     > RETURN                                                   null

End of function s1

Function s2:
Finding entry points
Branch analysis from position: 0
1 jumps found. (Code = 62) Position 1 = -2
filename:       /in/3gFWj
function name:  s2
number of ops:  4
compiled vars:  !0 = $val
line     #* E I O op                           fetch          ext  return  operands
-------------------------------------------------------------------------------------
   5     0  E >   RECV                                             !0      
   6     1        MAKE_REF                                         ~1      !0
         2      > RETURN                                                   ~1
   7     3*     > RETURN                                                   null

End of function s2

Comments

6

strval() is a function call, whereas cast is an internal typecast. Without having checked, I'd guess the cast is faster by a few cycles, but it shouldn't really make a difference.

2 Comments

Some benchmark for this also containing concatenation and interpolation: leifw.wickland.net/2009/08/…
This may have been correct in older version of PHP, I haven't verified that. But it's certainly not true anymore these days, because PHP now optimizes the function call away.
4

Late to the party, but according to PHPstorm (string) is faster

(string) is faster

2 Comments

Just to try to understand, because i don't find any sources of this, I did test it myself : 1000000 times of strval on 5.6.37 => 0.38586091995239 vs (string) => 0.30763101577759. And on 7.2.8, strval => 0.24432492256165 vs (string) => 0.24242401123047. Tried with a random double $double = 0.001614654;. So good to know but not a big difference there (and wonder what was the value for the up to 6x result). Using microtime(true).
For this warning to be displayed, you need the PHP Inspections (EA Extended) plugin. This is not displayed by default in PhpStorm.
2

There is an advantage of using strval() over (string), Which is we can use strval as a callback function, Something we cannot do with (string).

$arr = [1, 2, 3];
echo(json_encode($arr)); // [1,2,3]
$arr = array_map('strval', $arr);
echo(json_encode($arr)); // ["1","2","3"]

1 Comment

with "arrow" functions, you could simply do $arr = array_map(fn($s) => (string)$s, $arr);, classic anonymous function variant would be function ($s) { return (string)$s; }, all are pretty fast, in very very extreme cases strval can be a bit faster, probably due to direct translation to a native function call. But we're talking arrays with tens of thousands items and difference in miliseconds :-) So choose readability that suits you best.

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.