PHP Data Types, Variables, Constant, Operators Tutorial

In this tutorial, you will learn-

PHP Data Types

A Data type is the classification of data into a category according to its attributes;

PHP is a loosely typed language; it does not have explicit defined data types. PHP determines the data types by analyzing the attributes of data supplied. PHP implicitly supports the following data types

<?php
echo PHP_INT_MAX;
?>

Output:

9223372036854775807

Before we go into more details discussing PHP data types, let’s first discuss variables.

PHP Variable

A variable is a name given to a memory location that stores data at runtime.

The scope of a variable determines its visibility.

A Php global variable is accessible to all the scripts in an application.

A local variable is only accessible to the script that it was defined in.

Think of a variable as a glass containing water. You can add water into the glass, drink all of it, refill it again etc.

The same applies for variables. Variables are used to store data and provide stored data when needed. Just like in other programming languages, PHP supports variables too. Let’s now look at the rules followed when creating variables in PHP.

  Let’s now look at how PHP determines the data type depending on the attributes of the supplied data.

<?php
$my_var = 1;
echo $my_var;
?>

Output:

1

Floating point numbers

<?php
$my_var = 3.14;
echo $my_var;
?>

Output:

3.14

Character strings

<?php
$my_var ="Hypertext Pre Processor";
echo $my_var;
?>

Output:

Hypertext Pre Processor

 

Use of Variables

Variables help separate data from the program algorithms.

The same algorithm can be used for different input data values.

For example, suppose that you are developing a calculator program that adds up two numbers, you can create two variables that accept the numbers then you use the variables names in the expression that does the addition.

Variable Type Casting

Performing arithmetic computations using variables in a language such as C# requires the variables to be of the same data type.

Type casting is converting a variable or value into a desired data type.

This is very useful when performing arithmetic computations that require variables to be of the same data type.

Type casting in PHP is done by the interpreter.

In other languages such as C#, you have to cast the variables. The code below shows type casting in C#. The diagram below shows PHP implementing the above example.

 

YOU MIGHT LIKE: