start learning
Image 1
50101740112

PHP Types

PHP is a dynamically typed language, which means that variable types are determined at runtime, and you don't need to explicitly declare the type of a variable. PHP supports a variety of data types.

Here are some common PHP data types with definitions, examples, and clarifications:


Integer (int)

Integers are whole numbers without a decimal point.


$count = 42;
 

Integers can be both positive and negative numbers.


Float (float) or Double

Floats, also known as floating-point numbers, represent numbers with a decimal point.


$price = 19.99;
 

Floats can represent real numbers, but they may have limited precision due to the way they are stored.


String (string)

Strings represent sequences of characters enclosed in single ('') or double ("") quotes.


$name = "John";
 

Strings can include letters, numbers, symbols, and whitespace.


Boolean (bool)

Booleans have two possible values: true or false.


$isReady = true;
 

Booleans are often used for conditional statements and comparisons.


Array

Arrays are ordered, indexed collections of values.


$fruits = array("apple", "banana", "cherry");
 

PHP supports both indexed and associative arrays, where you can use numerical or named keys to access values.


Object

Objects are instances of user-defined classes and can hold both data (properties) and functions (methods).

See below for a class definition and object creation.


class Person {
    public $name;
    public function sayHello() {
        echo "Hello, my name is " . $this->name;
    }}

$person = new Person();
$person->name = "Alice";
 

Object-oriented programming is a fundamental concept in PHP.


Null

null represents the absence of a value.


$data = null;
 

Variables can be explicitly set to null or may have a null value if not assigned a value.


Resource

Resources are special variables that hold references to external resources, such as database connections or file handles.


$file = fopen("example.txt", "r");
 

Resources are not typically manipulated directly but are used with specific PHP functions.

Callable

Callables can hold references to functions or methods and can be invoked like a regular function.


$callback = 'myFunction';
 

Callables can be used with functions like call_user_func or as callbacks in various PHP functions.

These are some of the primary data types in PHP. Understanding these data types is essential for working with PHP variables and functions effectively. PHP also provides functions to check and convert between data types as needed during program execution.


×