Ad space (banner)
๐Ÿ˜PHP Lessons
Lesson 31 / 68

Type Conversion (Casting) Basics

In this lesson you will learn the basics of type conversion in PHP so you can move correctly between strings and numbers. This is for anyone searching for "PHP type conversion cast how to use".

Type conversion (casting) - string to number, number to string - is a fundamental programming operation. You use (int), (string), or functions such as intval(). Input from a user always arrives as text, so it must be converted before you can calculate with it.

The sample code converts the string "123" to a number with (int) and uses it in arithmetic, then converts the number 45 to a string with (string) and joins it to the word "dollars". This parenthesised cast notation is distinctly PHP; you rarely see it elsewhere.

A common stumbling block for beginners is what happens when the conversion fails. A string that cannot be converted to an int becomes 0, so instead of an error you quietly get the wrong value. Check first where it matters.

In real-world development, values coming from a form are always strings, so you must convert before doing monetary or date arithmetic. Type-aware code is the foundation of a stable application with fewer bugs.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run PHP directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)