PHP Tutorial menu

PHP Variables and Data Types

A variable is a named box that stores a value, like a name, a price or a list of marks.

Creating Variables

In PHP every variable name starts with a dollar sign $. You create a variable by giving it a value:

Example

php
<?php
$student = "Ali";
$age = 19;
$fee = 4500.50;

echo "$student is $age years old.";
Output
Ali is 19 years old.

You do not need to say what type the variable is. PHP works it out from the value.

Naming Rules

  • A name starts with $, then a letter or an underscore
  • It can contain letters, numbers and underscores only
  • It cannot start with a number: $2name is wrong
  • Names are case sensitive: $total and $Total are different

Choose clear names like $totalPrice or $total_price. A name like $x tells the reader nothing.

Data Types

TypeMeaningExample
stringText"Karachi"
intWhole number250
floatNumber with decimals99.95
boolTrue or falsetrue
arrayA list of values["red", "green"]
nullNo valuenull
objectAn instance of a classnew DateTime()

Use var_dump() to see both the type and the value:

Example

php
<?php
$name = "Ayesha";
$marks = 87;
$gpa = 3.6;
$passed = true;
$phone = null;

var_dump($name);
var_dump($marks);
var_dump($gpa);
var_dump($passed);
var_dump($phone);
Output
string(6) "Ayesha"
int(87)
float(3.6)
bool(true)
NULL

Doing Maths

PHP has the usual arithmetic operators:

OperatorMeaningExampleResult
+Add10 + 313
-Subtract10 - 37
*Multiply10 * 330
/Divide10 / 42.5
%Remainder10 % 31
**Power2 ** 38

Example

php
<?php
$price = 350;      // price of one notebook in Rs
$quantity = 4;
$total = $price * $quantity;
$total += 50;      // add Rs 50 delivery

echo "Total bill: Rs $total";
Output
Total bill: Rs 1450

$total += 50 is a short way to write $total = $total + 50. The same works with -=, *= and /=. To add 1, write $count++.

Constants

A constant is a value that never changes while the script runs. Create one with const or define(). Constants have no $ sign.

Example

php
<?php
const SHOP_NAME = "Saddar Electronics";
define("TAX_RATE", 0.18);

echo SHOP_NAME . " charges " . (TAX_RATE * 100) . "% tax.";
Output
Saddar Electronics charges 18% tax.

Type Conversion

You can convert a value to another type with a cast:

Example

php
<?php
$text = "42";
$number = (int) $text;
var_dump($number + 8);
Output
int(50)

Exercise

Exercise

Which line creates a valid PHP variable?

Learn PHP with a teacher

Join the Full Stack Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp