Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Type conversion in PHP

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 583
    Comment on it

    To convert variables of one type to another is known as type conversion. There are two types of type conversion:

    • Implicit type conversion
    • Explicit type conversion

    Implicit type conversion  : It automatically converts the data type to another.

    Case 1:

    Binary arithmetic operator : In this case if one is integer and other is floating-point number, then the first is also evaluated as the float. 

    If one is string and other is an integer, Then PHP automatically converts the string to an integer.

     

    Case 2:

    Boolean expression and expression operator : Where expression must be evaluated as a boolean, PHP converts the result of the expression to a boolean.

    Explicit type conversion : In this different type casting is used for conversion. These are :

    • (int) (integer) casts to an integer.
    • (float) ,(double) ,(real)  casts to a floating point number
    • (string) casts to a text string
    • (bool) (boolean) casts to a boolean value
    • (array) casts to an array
    • (object) casts to an object

    Some of the exaples are as below:

    Example 1 :

    Conversion to Integers
    
    <?php
    
      echo (int)5.999;
      echo "<br/>";
      echo (int)-7.54321;          // it will round toward zero
      echo "<br/>";
      echo (int)1000000000000;     // too big for an int !!!
      echo "<br/>";
    
    ?>
    
    Output:
    
    6
    -8
    -727379968(depending on your computer setup.)

    Example 2 :

    Conversions to Floating-Point Numbers
    
    
    <?php
    
      $f1 = (float)"+5555";             // float value: 5555.0
      $f2 = (float)"-123";              // -123.0
      $f3 = (float)"123.456";           // 123.456
      $f4 = (float)"1.23456e2";         // 123.456
      $f5 = (float)"1.234e-2";          // 0.001234
      $f6 = (float)"1000000000000";     // 1e12 (one trillion)
    
    ?>
    

    Example 3: 

    Conversion to Booleans
    
    
    <?php
    
      $b1 = (bool)0;                 // FALSE
      $b2 = (bool)0.0;               // FALSE
      $b4 = (bool)-10;               // TRUE
      $b5 = (bool)123123e-34;        // TRUE
      $b3 = (bool)(0.4 + 0.2  0.6); // TRUE  not EXACTLY 0.0 ...
    
    ?>

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: