Hello friends, here I am back again with the second basic tutorial of PHP and Today I am sharing the basics of type casting in PHP . If simply explained, type casting is a feature of any programming language to convert one data type to another data type value according to programmers convenience or compiler's. If the conversion is done by the compiler then it is called Implicit type casting and if it is done by the programmer then it is called Explicit type casting.
Consider the following code snippet of code :
Consider the following code snippet of code :
<?php $var1="2"; $var2=$var1+4; echo $var2; ?>In the above code the implicit type casting is explained. As you can see in the code that the $var1 is initialized with a string value which is then added with a integer value the resulting integer value is stored in $var2. Next, let us take a look on explicit type conversion :
<?php echo gettype($var1); echo gettype($var2); settype($var2,"string"); $var3=(int)$var2; echo gettype($var3); ?>As you can see in the above code, first I have found the type of a php variable using gettype() and then set the type of a variable using settype(). I have also demonstrated that how you can change data type of a variable by explicitly specifying the datatype as in the case of $var3 where I have used the int datatype. Below is a list of method that may come handy while you are dealing with type casting :
Is Boolean : <?php echo is_bool($var1); ?> Is Array : <?php echo is_array($var1); ?> Is Float : <?php echo is_float($var1); ?> Is Int : <?php echo is_int($var1); ?> Is Null : <?php echo is_null($var1); ?> Is Numeric : <?php echo is_numeric($var1); ?> Is String : <?php echo is_string($var1); ?>
0 comments:
Post a Comment
Note: only a member of this blog may post a comment.