Web Development

This part is of the PHP Post Series dedicated to spread knowledge about PHP

PHP, like most programming languages, have data types. Data types are types of data being stored. Each has their own unique characteristics with regards to size, number of elements, etc.

In PHP, there are a couple of data types available:

Data Type Description
string a sequence of letters, symbols and numbers including spaces
integer a sequence of numbers. Can be hexadecimal, octal, binary, decimal
float can be called double. A sequence of numbers usually with decimal points
array is a map of key-value pairs
object acts like real world objects with characteristics, states and methods or actions

Getting a value’s data type:

$a = "Thorpe Obazee";
echo gettype($a)."\n";
$b = 12345;
echo gettype($b)."\n";
$c = 12345.78;
echo gettype($c)."\n";
$d = array('I', 'rock');
echo gettype($d)."\n";
$e = true;
echo gettype($e)."\n";
string
integer
double
array
boolean

Typecasting

Data types can be converted into other data types. This is what type casting does. Here are a few examples

$a = (int) "Thorpe Obazee";
echo gettype($a)."\n";
$b = (int) "rocking in 2014";
echo gettype($b)."\n";
echo $b;
$c = (int) true;
echo gettype($c);
echo $c;
$d = (bool) "false"
echo $d;
$e = (bool) 0;
echo $e;
$f = (bool) "0.0"
echo $f;
integer
integer
2014
integer
1
false
false
false

Typecasting using settype()

(int), (string), (bool) and others are usually used to typecast values. However, there is built in function in PHP that does also does that.

$a = "Thorpe Obazee";
settype($a, "int");
echo gettype($a)."\n";
$b = "rocking in 2014";
settype($b, "int");
echo gettype($b)."\n";
echo $b;
integer
integer
2014