PHP Tutorial
Control Statement
PHP Programs
PHP Functions
PHP Arrays
PHP Strings
PHP Math
PHP Form
PHP Include
State Management
PHP File

PHP Variables

In PHP, both echo and print are used to output strings, but there are some differences between them. Here is a comparison of the two:

Declaring Variables

  • Variables in PHP are declared with a dollar sign ($) followed by the variable name.
  • Variable names must start with a letter or an underscore (_), followed by any number of letters, numbers, or underscores.
  • Variable names are case-sensitive.

Syntax

				
					$variableName = value;
				
			

Example

				
					<?php
$greeting = "Hello, world!";
$number = 42;
$floatNumber = 3.14;
$isTrue = true;
?>

				
			

Variable Types

PHP supports various data types for variables, including:

  • String: Sequence of characters.
  • Integer: Whole numbers.
  • Float (or double): Floating point numbers.
  • Boolean: True or false.
  • Array: Collection of values.
  • Object: Instance of a class.
  • NULL: Variable with no value.

Examples of Different Types

				
					<?php
$stringVar = "Hello, world!";  // String
$intVar = 42;                 // Integer
$floatVar = 3.14;             // Float
$boolVar = true;              // Boolean
$arrayVar = array(1, 2, 3);   // Array

// Object example
class MyClass {
    public $property = "Hello, class!";
}

$objectVar = new MyClass();   // Object

// NULL example
$nullVar = NULL;              // NULL
?>

				
			

Variable Scope

Variables can have different scopes:

  • Local Scope: Variables declared within a function.
  • Global Scope: Variables declared outside any function.
  • Static Scope: Variables that retain their value across function calls.

Example of Scope

				
					<?php
$globalVar = "I'm global";

function myFunction() {
    $localVar = "I'm local";
    global $globalVar;  // To access the global variable
    echo $globalVar;
    static $staticVar = 0;  // Static variable
    $staticVar++;
    echo $staticVar;
}

myFunction();
myFunction();
?>
 
				
			

Superglobals

PHP has several predefined variables known as superglobals, which are accessible from any scope within a script. Some examples include:

  • $_GET
  • $_POST
  • $_SESSION
  • $_COOKIE
  • $_SERVER
  • $_FILES
  • $_REQUEST
  • $_ENV

Example of Superglobals

				
					<?php
// Accessing data sent via a form using POST method
$name = $_POST['name'];
echo "Hello, " . $name;

// Accessing server information
echo "Server name: " . $_SERVER['SERVER_NAME'];
?>

				
			
Scroll to Top