Home ยป Tutorial on PHP Variables

Tutorial on PHP Variables

Variables in PHP are used to store data that can be manipulated and retrieved throughout your program.

They are dynamically typed, meaning the data type is determined at runtime.

PHP variables are prefixed with a $ sign and can hold various types of data such as integers, strings, arrays, and objects.

This tutorial covers:

1. Basics of PHP Variables

In PHP, variables are created by assigning a value using the = operator.

Example: Declaring and Using Variables

<?php
$name = "John";        // String
$age = 25;             // Integer
$isStudent = true;     // Boolean
$height = 5.9;         // Float

echo "Name: $name\n";
echo "Age: $age\n";
echo "Is a student: $isStudent\n";
echo "Height: $height\n";
?>

Output:

Name: John
Age: 25
Is a student: 1
Height: 5.9

2. Variable Naming Rules

  • Variable names must start with a $ symbol.
  • The first character after $ must be a letter or underscore.
  • Variable names can include letters, numbers, and underscores.
  • Variable names are case-sensitive ($name and $Name are different).

Examples: Valid and Invalid Variable Names

<?php
$var1 = "Valid";      // Valid
$_var2 = "Valid";     // Valid
$Var_3 = "Valid";     // Valid
// $3var = "Invalid"; // Invalid: cannot start with a number
// $var-3 = "Invalid"; // Invalid: cannot contain hyphens
?>

3. Variable Types

PHP supports multiple data types, including:

  • String
  • Integer
  • Float (Double)
  • Boolean
  • Array
  • Object
  • NULL

Example: Working with Different Types

<?php
$string = "Hello, World!";
$integer = 42;
$float = 3.14;
$boolean = true;
$array = ["Apple", "Banana", "Cherry"];
$object = (object) ['name' => 'John', 'age' => 30];
$nullVar = null;

echo "String: $string\n";
echo "Integer: $integer\n";
echo "Float: $float\n";
echo "Boolean: $boolean\n";
echo "Array: " . implode(", ", $array) . "\n";
echo "Object Name: {$object->name}\n";
echo "Null Variable: " . ($nullVar === null ? "NULL" : "Not NULL") . "\n";
?>

Output:

String: Hello, World!
Integer: 42
Float: 3.14
Boolean: 1
Array: Apple, Banana, Cherry
Object Name: John
Null Variable: NULL

4. Constants

Constants are variables with a fixed value. Use the define() function or const keyword to declare them.

Example: Defining Constants

<?php
define("PI", 3.14159);  // Using define()
const GRAVITY = 9.8;    // Using const

echo "PI: " . PI . "\n";
echo "Gravity: " . GRAVITY . "\n";
?>

Output:

PI: 3.14159
Gravity: 9.8

5. Variable Scope

The scope of a variable determines where it can be accessed:

  • Global: Accessible everywhere.
  • Local: Accessible only within the function where it’s defined.
  • Static: Retains its value between function calls.

Example: Global and Local Variables

<?php
$globalVar = "Global";

function testScope() {
    $localVar = "Local";
    echo "Inside function: $localVar\n";
    // echo "Inside function: $globalVar"; // Error
}

testScope();
echo "Outside function: $globalVar\n";
// echo "Outside function: $localVar"; // Error
?>

Output:

Inside function: Local
Outside function: Global

Example: Using global Keyword

<?php
$globalVar = "Global";

function useGlobal() {
    global $globalVar;
    echo "Accessed inside function: $globalVar\n";
}

useGlobal();
?>

Output:

Accessed inside function: Global

Example: Static Variables

<?php
function staticCounter() {
    static $count = 0;
    $count++;
    echo "Count: $count\n";
}

staticCounter();
staticCounter();
staticCounter();
?>

Output:

Count: 1
Count: 2
Count: 3

6. Superglobals

PHP provides several built-in superglobal variables, such as:

  • $_GET: Retrieves data sent via URL parameters.
  • $_POST: Retrieves data sent via HTTP POST.
  • $_SERVER: Provides server and execution environment information.
  • $_SESSION: Stores session data.

Example: Using $_GET

<?php
// Access via URL: example.php?name=John&age=25
$name = $_GET['name'];
$age = $_GET['age'];

echo "Name: $name, Age: $age\n";
?>

7. Practical Examples

Example 1: Swap Two Variables

<?php
$a = 10;
$b = 20;

echo "Before swap: a = $a, b = $b\n";

$temp = $a;
$a = $b;
$b = $temp;

echo "After swap: a = $a, b = $b\n";
?>

Output:

Before swap: a = 10, b = 20
After swap: a = 20, b = 10

Example 2: Checking Data Types

<?php
$var = 42;

if (is_int($var)) {
    echo "The variable is an integer.\n";
} elseif (is_string($var)) {
    echo "The variable is a string.\n";
} elseif (is_bool($var)) {
    echo "The variable is a boolean.\n";
}
?>

Output:

The variable is an integer.

Example 3: Simple Interest Calculator

<?php
$principal = 1000;
$rate = 5; // in percentage
$time = 2; // in years

$simpleInterest = ($principal * $rate * $time) / 100;

echo "Principal: $principal\n";
echo "Rate: $rate%\n";
echo "Time: $time years\n";
echo "Simple Interest: $simpleInterest\n";
?>

Output:

Principal: 1000
Rate: 5%
Time: 2 years
Simple Interest: 100

Example 4: Random Number Generator

<?php
$randomNumber = rand(1, 100);
echo "Random Number: $randomNumber\n";
?>

Output:

Random Number: 57

Summary

In this tutorial, we covered:

  1. Basics of Variables: How to declare and use variables.
  2. Variable Types: Different data types in PHP.
  3. Constants: How to define fixed values.
  4. Variable Scope: Understanding global, local, and static variables.
  5. Superglobals: Using $_GET, $_POST, and others.
  6. Practical Examples: Real-world use cases.

You may also like