04 – PHP Data Types

In PHP, variables can store data of different types. The following data types can be used in PHP:

  • String
  • Integer
  • Float
  • Boolean
  • Array
  • Object
  • NULL
  • Resource (advanced topic)

PHP strings

In PHP, a string can be any sequence of characters placed in between quotation marks. Both, single and double quotation marks can be used but they are slightly different.

<?php

$a = 4;
$b = 5;
$c = "Hi there! $a + $b";
$d = 'Hi there! $a + $b';
echo $c; // It prints Hi there! 4 + 5
echo "<br>";
echo $d; // It prints Hi there! $a + $b 

?>

PHP Integers

An integer is a number between -2,147,483,648 and 2,147,483,647. An integer must have at least one digit, it must not have a decimal point and it can be positive or negative.

Integers can be specified in three formats: decimal (10-based), hexadecimal (16-based – prefixed with 0x) or octal (8-based – prefixed with 0).

<?php

$a = 4;
$b = 587;
$c = -39;

echo $a;
echo "<br>";
echo $b;
echo "<br>";
echo $c;
echo "<br>";

var_dump($a);

?>

PHP float

In PHP, a float is a number with a decimal point. It also can be a number in exponential form.

<?php

$a = 5.294;
$b = 10.2e3;
$c = 3E-10;

echo $a;
echo "<br>";
var_dump($a);
echo "<br><br>";

echo $b;
echo "<br>";
var_dump($b);
echo "<br><br>";

echo $c;
echo "<br>";
var_dump($c);

?>

PHP Boolean

In PHP, a Boolean data type can have only a value of true or false. Boolean data type is usually used in conditional testing.

<?php

$a = true;
$b = false;

var_dump($a);
echo "<br>";
var_dump($b);

?>

PHP Array

In PHP, an array is a variable that stores multiple values.

<?php

$a = array("HTML", "CSS", "Python", "JavaScript", "PHP");

var_dump($a);
echo "<br>";
echo $a;

?>

The code will print:

array(5) { [0]=> string(4) "HTML" [1]=> string(3) "CSS" [2]=> string(6) "Python" [3]=> string(10) "JavaScript" [4]=> string(3) "PHP" }
Array 

PHP Object

In PHP, an object is a data type which stores data and information on how to process that data. In PHP, an object must be explicitly declared. First, a class of object has to be declared using the keyword class. A class can contain properties and methods.

<?php

class Language {
    function Language() {
        $this->model = "HTML";
        $this->difficulty = "easy";
    }
}
// create an object
$oneLang = new Language();

// show object properties
echo $oneLang->model;
echo $oneLang->difficulty;

?>

PHP Null

In PHP, the data type Null can have a single value of Null. A variable which is not assigned a value, will have a value of Null. Setting a variable’s value to Null is a common way of emptying a variable.

<?php

$a = "Hi there!";
echo $a;

$a = null;
echo "<br><br>";
echo $a;
echo "<br>";
var_dump($a);

?>

Leave a Reply