PHP: Convert Integer Variable to String Variable
Tutorial by Anja Proggy | Last update on 2024-04-18 | Created on 2014-03-19
Sooner or later, a newbie in PHP programming comes to the question of how to convert, transform or rewrite a variable specified as a specific type to another type.
Especially if someone is coming from other programming languages in which it is not possible to simply attach a number type to a string type, this question is reasonable in PHP. This is why I came to the idea of writing this small tutorial.
Automatic Type Conversion
In terms of types, PHP is a very liberal. For example, if you would like to output a number as text, it is sufficient to pass the variable containing the number:
echo $zahl;
In this case, PHP is doing the type conversion automatically. Also many functions like substr(), for example, are also accepting numbers as parameter which are then processed as string. Therefore, in most cases, you do not have to care about types in PHP.
Explicit Type Conversion
If you nevertheless would like to do a type casting in PHP explicitly, you can proceed in this way, for instance:
$text = $zahl . ''; $text = (string) $zahl; $zahl = (int) $text;
It is sufficient to attach an empty string to a number - and the number becomes a string. Alternatively, you can also write the type in brackets in front of the variable to implement the type transformation. For example, the following keywords are allowed for this:
- (int) and (integer) for type casting to an integer number
- (float), (double) and (real) for type casting to a float number
- (string) for the transformation of the variable to a string
- (bool) or (boolean) for the type conversion to boolean
Others are (array), (object) or (unset) for a cast to null. But I think, you will need them very seldom.
About the Author
The author has not added a profile short description yet.
Show Profile
Related Topics
PHP: Check Strings with Ctype-Functions for Character Classes
Article | 0 Comments
PHP: Get first Digit of Number or String
Tutorial | 0 Comments
Rewrite Text Files with a fixed Line Length
Tutorial | 0 Comments
Delphi: System-Wide HotKey
Tutorial | 1 Comment
How to Replace multiple Texts at the same Time
Tutorial | 0 Comments
Android Programming: Receive Responce from HTTP POST Request
Tutorial | 0 Comments
Convert many CSV Files to XLSX or ODS Spreadsheets
Tutorial | 0 Comments
Important Note
Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.
Participate
Ask your own question or write your own article on askingbox.com. That’s how it’s done.