PHP: Explicit conversion

Type conversion is a very frequent operation in web development. On one hand, we can count on weak type system, on the other hand, it's often better to convert types explicitly, using special syntax. Such code is easier to understand and more predictable.

// These examples are somewhat artificial. In reality this mechanism comes in handy when used on variables.

printr((string) 5);
r((int) '345');

To execute a explicit conversion we cast the desirable type in brackets before the value. As result the value on the right will be converted into type casted in brackets. At this moment we are familiar only with two types, but type casting works with all types.

Type casting can be used inside compound expressions:


//Additional brackets help to distinguish parts of expression visually

print_r('This is ' . ((string) 5));
  This is 5

In more complex cases (when used in functions, we will learn about that later) it's common to encounter multiple conversions (string) (5 + ((int) '4')). The calculation order of this expression is as follows:


(int) '4';  // 4
5 + 4;      // 9
(string) 9; // '9'


Output the string 2 times as result of integer 2 and string times, using type casting and concatenation.

If you got stuck and don't know what to do, you can ask a question in our huge and friendly community