Web Development /PHP Programming / Lesson
Web Development

Data Types

Learn the major PHP data types, including strings, integers, floats, booleans, arrays, null, objects, resources, type checking, type conversion, and practical data handling.

🎯

Learning Objectives

["Understand what data types are and why they matter in PHP.","Identify the major data types supported by PHP.","Work with strings and understand basic string values.","Work with integers and floating-point numbers.","Understand boolean values and logical states.","Create and inspect arrays.","Understand the null data type.","Recognize objects and resources as PHP data types.","Use gettype(), var_dump(), and related tools to inspect values.","Understand automatic and explicit type conversion in PHP."]

📖

Lesson Content

Data Types in PHP

Every value used by a PHP program has a data type. A data type tells PHP what kind of information a value represents and determines how that value can be used.

For example, a person’s name is usually represented as a string, a person’s age can be represented as an integer, a product price can be represented as a floating-point number, and a yes-or-no state can be represented as a boolean.

Understanding data types is important because different types of values behave differently when they are stored, displayed, compared, calculated, or passed to functions.

What Is a Data Type?

A data type describes the kind of value stored in a variable or produced by an expression.

For example:

<?php

$name = "David";
$age = 25;
$price = 1500.50;
$is_active = true;

?>

These variables contain different types of values.

  • $name contains a string.
  • $age contains an integer.
  • $price contains a float.
  • $is_active contains a boolean.

PHP’s Main Data Types

PHP supports several important data types.

  • String
  • Integer
  • Float
  • Boolean
  • Array
  • Object
  • Null
  • Resource

The first six types are especially important when learning PHP application development.

1. String

A string is a sequence of characters. Strings are used for text such as names, addresses, messages, usernames, and course titles.

<?php

$name = "David";

echo $name;

?>

Strings can be written using single or double quotation marks.

<?php

$course = 'PHP Programming';

$title = "Web Development";

?>

String Concatenation

The dot operator can be used to join strings together.

<?php

$first_name = "David";
$last_name = "Ade";

$full_name = $first_name . " " . $last_name;

echo $full_name;

?>

String Interpolation

Variables can also be inserted into double-quoted strings.

<?php

$name = "David";

echo "Welcome, $name";

?>

2. Integer

An integer is a whole number without a decimal portion.

Examples include:

0
10
25
100
-50

PHP variables can store integer values directly.

<?php

$age = 25;
$students = 150;
$score = 85;

echo $age;

?>

Integers can be used in mathematical operations.

<?php

$price = 5000;
$quantity = 3;

$total = $price * $quantity;

echo $total;

?>

3. Float

A float, also called a floating-point number, is a number that contains a decimal portion.

<?php

$price = 1500.50;
$temperature = 28.5;
$percentage = 75.25;

?>

Floats are useful when working with values such as prices, measurements, percentages, and averages.

<?php

$price = 2500.50;
$quantity = 2;

$total = $price * $quantity;

echo $total;

?>

Integer vs Float

The difference between an integer and a float is that an integer represents a whole number while a float can represent a decimal number.

<?php

$whole_number = 100;
$decimal_number = 100.50;

?>

PHP can automatically determine that these values have different types.

4. Boolean

A boolean represents one of two logical values:

  • true
  • false

Booleans are commonly used in conditions and application states.

<?php

$is_logged_in = true;
$is_admin = false;

?>

For example:

<?php

$is_logged_in = true;

if ( $is_logged_in ) {

	echo "Welcome to your dashboard.";

}

?>

Boolean values are especially important when building authentication systems, permission systems, validation rules, and conditional logic.

5. Array

An array allows multiple values to be stored in a single variable.

<?php

$courses = array(
	"PHP",
	"JavaScript",
	"Python"
);

?>

PHP also supports short array syntax.

<?php

$courses = [
	"PHP",
	"JavaScript",
	"Python"
];

?>

Individual array elements can be accessed using their indexes.

<?php

$courses = [
	"PHP",
	"JavaScript",
	"Python"
];

echo $courses[0];

?>

The first element has an index of 0.

Associative Arrays

Associative arrays use named keys instead of numeric indexes.

<?php

$student = [
	"name" => "David",
	"age" => 25,
	"course" => "PHP"
];

echo $student["name"];

?>

Associative arrays are extremely useful when representing structured information.

Multidimensional Arrays

An array can contain other arrays.

<?php

$students = [
	[
		"name" => "David",
		"course" => "PHP"
	],
	[
		"name" => "Sarah",
		"course" => "JavaScript"
	]
];

echo $students[0]["name"];

?>

Multidimensional arrays are commonly used when working with collections of records.

6. Null

The null data type represents the absence of a value.

<?php

$middle_name = null;

?>

A variable can be assigned null when it intentionally has no value.

For example, an optional database field may contain null when no information has been provided.

Checking for Null

The is_null() function can be used to determine whether a value is null.

<?php

$value = null;

if ( is_null( $value ) ) {

	echo "The value is null.";

}

?>

The isset() function can also be useful when checking whether a variable exists and is not null.

7. Object

An object is an instance of a class. Objects are a major part of object-oriented programming in PHP.

<?php

class Student {

	public $name;

}

$student = new Student();

$student->name = "David";

echo $student->name;

?>

Objects allow developers to group data and behavior into reusable structures.

Object-oriented PHP will be studied in greater detail later in this module.

8. Resource

A resource is a special type used by PHP to represent a reference to an external resource. Historically, resources have been used for things such as certain file handles and external connections.

Resources are less common in everyday modern PHP application code because many APIs now return objects or other values instead.

Checking Data Types

PHP provides several functions that can help developers determine the type of a value.

gettype()

The gettype() function returns the type of a value as a string.

<?php

$age = 25;

echo gettype( $age );

?>

The result will indicate that the value is an integer.

var_dump()

The var_dump() function displays detailed information about a variable, including its type and value.

<?php

$name = "David";

var_dump( $name );

?>

This is particularly useful when debugging PHP applications.

Type Checking Functions

PHP provides specific functions for checking whether a value belongs to a particular type.

Examples include:

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

For example:

<?php

$age = 25;

if ( is_int( $age ) ) {

	echo "Age is an integer.";

}

?>

is_string()

<?php

$name = "David";

if ( is_string( $name ) ) {

	echo "The value is a string.";

}

?>

is_numeric()

The is_numeric() function can be used to determine whether a value is numeric or can be interpreted as a number.

<?php

$value = "100";

if ( is_numeric( $value ) ) {

	echo "The value is numeric.";

}

?>

Type Conversion

Type conversion occurs when a value is converted from one data type to another.

PHP can perform automatic type conversion in some situations.

<?php

$number = "10";

$result = $number + 5;

echo $result;

?>

PHP may interpret the numeric string as a number during the calculation.

Developers should still be careful when relying on automatic conversions, especially when processing user input.

Explicit Type Casting

A developer can explicitly request a type conversion using casting.

Convert to Integer

<?php

$value = "25";

$number = (int) $value;

echo $number;

?>

Convert to Float

<?php

$value = "25.75";

$number = (float) $value;

echo $number;

?>

Convert to String

<?php

$number = 100;

$text = (string) $number;

echo $text;

?>

Convert to Boolean

<?php

$value = 1;

$result = (bool) $value;

var_dump( $result );

?>

Type Juggling

PHP is a dynamically typed language, meaning a variable does not normally need a type declaration when it is created.

<?php

$value = "Hello";

$value = 100;

$value = true;

?>

The same variable can hold different types of values at different points in a program.

This flexibility can be convenient, but developers must understand the values being handled to avoid unexpected behavior.

Strict Types

PHP also supports stricter type behavior through the declare(strict_types=1) directive.

<?php

declare(strict_types=1);

function add_numbers(int $a, int $b): int {

	return $a + $b;
}

echo add_numbers(10, 20);

Strict typing becomes especially useful in larger applications because it can make function behavior more predictable.

Type Declarations

Modern PHP allows developers to declare expected types for function parameters, return values, properties, and other structures.

<?php

function greet(string $name): string {

	return "Hello " . $name;

}

echo greet("David");

?>

Here, the function expects a string parameter and declares that it returns a string.

Boolean Values in Conditions

Different values can behave as true or false when used in conditional expressions. Developers should understand these rules when writing application logic.

<?php

$name = "";

if ( $name ) {

	echo "A name was provided.";

} else {

	echo "No name was provided.";

}

?>

For security-sensitive or data-validation logic, explicit checks are often preferable to relying on automatic truthiness behavior.

Data Types and User Input

User input often arrives as strings, even when the user intends to submit a number.

For example, a form may submit an age as text:

$age = "25";

If the application expects an integer, the value should be validated and converted appropriately before being used.

<?php

$age = "25";

if ( is_numeric( $age ) ) {

	$age = (int) $age;

	echo $age;

}

?>

In real applications, validation should be more comprehensive than simply checking whether a value is numeric.

Data Types and Databases

Data types become especially important when PHP communicates with databases.

A database may contain values representing names, dates, prices, quantities, status values, and other information. PHP applications need to correctly interpret and validate these values when processing database records.

For example, a student record could contain:

<?php

$student = [
	"name" => "David",
	"age" => 25,
	"score" => 87.5,
	"active" => true
];

?>

Each piece of information has a different logical type.

Practical Example

<?php

$student_name = "David";
$age = 25;
$average_score = 82.5;
$is_registered = true;

echo "Name: " . $student_name;
echo "<br>";
echo "Age: " . $age;
echo "<br>";
echo "Average Score: " . $average_score;
echo "<br>";
echo "Registered: ";

if ( $is_registered ) {

	echo "Yes";

} else {

	echo "No";

}

?>

This example demonstrates how strings, integers, floats, and booleans can work together in a simple PHP application.

Common Data Type Mistakes

Beginners often encounter problems when they assume a value has a different type from the one PHP is actually using.

Common mistakes include:

  • Treating a numeric string as an integer without validation.
  • Comparing values without understanding type conversion.
  • Assuming all form values are already correctly typed.
  • Using a string where an array is expected.
  • Trying to access a property on a value that is not an object.
  • Ignoring null values.
  • Failing to validate data before using it.

Practical Exercise

Create a file named data-types.php.

Your program should create variables for:

  • Your name as a string.
  • Your age as an integer.
  • Your course fee as a float.
  • Your enrollment status as a boolean.
  • A list of three courses as an array.
  • An optional value set to null.

Use var_dump() to inspect each value and identify its data type.

Summary

PHP supports several important data types, including strings, integers, floats, booleans, arrays, objects, null, and resources.

Understanding data types helps developers write reliable programs, perform correct calculations, validate information, and process data safely.

PHP is dynamically typed, but developers can use type declarations and strict typing to make applications more predictable.

In the next lesson, we will learn about PHP operators and how they are used to perform calculations, comparisons, assignments, and logical operations.

💻

Code Example

<?php

$name = "David";
$age = 25;
$course_fee = 150000.50;
$is_registered = true;

$courses = [
	"PHP",
	"JavaScript",
	"Python"
];

$optional_value = null;

echo "Name: " . $name . "<br>";
echo "Age: " . $age . "<br>";
echo "Course Fee: " . $course_fee . "<br>";

echo "Registered: ";

if ( $is_registered ) {
	echo "Yes";
} else {
	echo "No";
}

echo "<br>";
echo "Courses:<br>";

foreach ( $courses as $course ) {
	echo $course . "<br>";
}

echo "<br>Data Type Information:<br>";

var_dump( $name );
var_dump( $age );
var_dump( $course_fee );
var_dump( $is_registered );
var_dump( $courses );
var_dump( $optional_value );

?>
⭐

Key Takeaways

["Every PHP value has a data type.","Important PHP data types include string, integer, float, boolean, array, object, null, and resource.","Strings represent text.","Integers represent whole numbers.","Floats represent decimal numbers.","Booleans represent true or false states.","Arrays store multiple values in a single variable.","Null represents the absence of a value.","gettype(), var_dump(), and type-checking functions help developers inspect values.","PHP can automatically convert types in some situations, while explicit casting can be used when a specific type is required."]

Enjoying this lesson?

Sign in to your Dwallnet Academy student account to track your learning progress and mark lessons as complete.

Sign In to Track Progress