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
$student = "Ali";
$age = 19;
$fee = 4500.50;
echo "$student is $age years old.";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:
$2nameis wrong - Names are case sensitive:
$totaland$Totalare different
Choose clear names like $totalPrice or $total_price. A name like $x tells the reader nothing.
Data Types
| Type | Meaning | Example |
|---|---|---|
| string | Text | "Karachi" |
| int | Whole number | 250 |
| float | Number with decimals | 99.95 |
| bool | True or false | true |
| array | A list of values | ["red", "green"] |
| null | No value | null |
| object | An instance of a class | new DateTime() |
Use var_dump() to see both the type and the value:
Example
<?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);string(6) "Ayesha" int(87) float(3.6) bool(true) NULL
Doing Maths
PHP has the usual arithmetic operators:
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | Add | 10 + 3 | 13 |
- | Subtract | 10 - 3 | 7 |
* | Multiply | 10 * 3 | 30 |
/ | Divide | 10 / 4 | 2.5 |
% | Remainder | 10 % 3 | 1 |
** | Power | 2 ** 3 | 8 |
Example
<?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";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
const SHOP_NAME = "Saddar Electronics";
define("TAX_RATE", 0.18);
echo SHOP_NAME . " charges " . (TAX_RATE * 100) . "% tax.";Saddar Electronics charges 18% tax.
Type Conversion
You can convert a value to another type with a cast:
Example
<?php
$text = "42";
$number = (int) $text;
var_dump($number + 8);int(50)
Exercise
Exercise
Which line creates a valid PHP variable?
