Variables and Data Types

Site Admin · 11 Sep 2026 · 8 views

Variables and Data Types

PHP variables are loose: you do not declare a type, and the interpreter decides the type from the value you assign.

Declaring variables

Variables start with a dollar sign and a letter or underscore:

<?php
$greeting = 'Hello';
$count    = 3;
$price    = 19.99;
$active   = true;

Scalar types

Strings hold text, integers hold whole numbers, floats hold decimals, and booleans hold true or false. None of these need quotes except strings.

Compound types

Arrays and objects hold collections. A quick array example:

$colors = ['red', 'green', 'blue'];
echo $colors[0];
$user = ['name' => 'Ada', 'role' => 'admin'];
echo $user['role'];

Type juggling

PHP converts types as needed. Adding a string and a number works:

$result = '10' + 5;   // int 15
var_dump($result);

This flexibility is convenient but can hide bugs, so validate input and use strict comparisons.

Strict typing

You can opt into strict mode per file:

<?php declare(strict_types=1);

With strict types enabled, function arguments and returns must match declared types, which catches many silent mistakes.

Checking types

Use gettype to inspect a value and the is_string, is_int, and is_array functions to branch on what you receive.

Key Points

  • Variables start with a dollar sign.
  • Types are inferred from assigned values.
  • Scalars: string, int, float, bool.
  • Arrays and objects hold collections.
  • declare(strict_types=1) tightens coercion.
Share this post:

Comments (0)

Please login or register to comment.