CodeMIRAI
0 XP

Variables and types

2 min read 6 runnable examples Quiz included

PHP variables start with a dollar sign. You don't declare a type; PHP works it out from the value.

PHP
<?php
$name = "Asha";
$age = 21;
$height = 1.65;
$isMember = true;

echo "$name is $age years old\n";
var_dump($name, $age, $height, $isMember);

var_dump() shows a value's type and contents, which makes it the go-to debugging tool in PHP.

Types

TypeExample
string"hello"
int42
float3.14
booltrue, false
array[1, 2, 3]
nullnull (no value)
PHP
<?php
echo gettype(42), "\n";
echo gettype("42"), "\n";
echo gettype(4.2), "\n";
echo gettype(null), "\n";

Type juggling

PHP converts types automatically when it thinks it should:

PHP
<?php
var_dump("5" + 3);       // int(8): the string becomes a number
var_dump("5" . 3);       // string "53": . always joins text
var_dump(10 / 4);        // float(2.5)
var_dump(intdiv(10, 4)); // int(2)

Comparing: == versus ===

PHP
<?php
var_dump(5 == "5");      // true: compares values after conversion
var_dump(5 === "5");     // false: compares value AND type
var_dump(0 == "a");      // false in PHP 8
var_dump(null == false); // true

Use === unless you specifically want conversion.

Constants

PHP
<?php
define("SITE_NAME", "CodeMIRAI");
const TAX_RATE = 0.18;
echo SITE_NAME . " charges " . (TAX_RATE * 100) . "% tax\n";

Constants have no $ and can't be changed.

Checking for a value

PHP
<?php
$email = null;
var_dump(isset($email));     // false: null or not set
var_dump(empty(""));         // true: empty-ish values
echo $email ?? "no email", "\n";   // null coalescing: a default
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.