Type Casting

Explicitly converts data types

 

(target data type)identifier

 

<?php
	$myFloat = 42.666 ; //define a float
	$myInteger = (int)$myFloat ; //type cast it as an int
	echo $myInteger ;

	$myInt = (int) 52.648 ; //or do both at the same time
	echo $myInt;
?>

Displays:

42

52

 

<?php
	$myInt = 123 ;
	$myFloat = 12.34 ;

	echo "\$myInt, " . $myInt . ", is of data type: " . gettype($myInt) . "<br>";

	echo "\$myFloat, " . $myFloat . ", is of data type: " . gettype($myFloat) . "<br>";
?>

Displays:

$myInt, 123, is of data type: integer
$myFloat, 12.34, is of data type: double

 

 

To test a certain datatype:

  • is_string()
  • is_float()
  • is_int()
  • is_bool()
  • is_array()
  • is_object()
  • is_resource()
  • is_null()

Leave a Reply