PHP Type Conversion

PHP is a loosely typed language, meaning it automatically converts variables from one data type to another when needed. This process is called type juggling. However, you can also manually convert a variable’s type using type casting.

1. Automatic Type Conversion (Type Juggling)

PHP automatically converts data types based on the operation performed. This is called type juggling.

<?php
    $num = "10"; // String
    $sum = $num + 5; // PHP converts string to integer automatically

    echo $sum; // Outputs: 15
    var_dump($sum); // int(15)
?>

Try It Now

2. Manual Type Conversion (Type Casting)

Type casting allows explicit conversion of variables to a specific data type using the following syntax:

  • (int) – Convert to integer
  • (float) or (double) – Convert to floating-point number
  • (bool) – Convert to boolean
  • (string) – Convert to string
  • (array) – Convert to array
  • (object) – Convert to object
  • (unset) – Convert to NULL

3. Examples of Type Casting

Convert String to Integer

<?php
    $value = "25";
    $intValue = (int)$value;

    echo $intValue; // Outputs: 25
    var_dump($intValue); // int(25)
?>

Try It Now

Convert Float to Integer

<?php
    $price = 10.75;
    $intPrice = (int)$price;

    echo $intPrice; // Outputs: 10
?>

Try It Now

Convert Integer to String

<?php
    $num = 100;
    $strNum = (string)$num;

    echo $strNum; // Outputs: 100
    var_dump($strNum); // string(3) "100"
?>

Try It Now

Convert Array to Object

<?php
    $arr = ["name" => "John", "age" => 30];
    $obj = (object)$arr;

    echo $obj->name; // Outputs: John
?>

Try It Now

Convert Value to Boolean

<?php
    $val1 = 0;
    $val2 = 1;
    $val3 = "hello";

    var_dump((bool)$val1); // bool(false)
    var_dump((bool)$val2); // bool(true)
    var_dump((bool)$val3); // bool(true)
?>

Try It Now

4. Using settype() for Type Conversion

The settype() function changes the type of a variable directly.

<?php
    $var = "123";
    settype($var, "int");

    echo $var; // Outputs: 123
    var_dump($var); // int(123)
?>

Try It Now

Conclusion

PHP supports both automatic and manual type conversion. Understanding these concepts helps in handling data effectively.