PHP Variable
PHP variables are used to store data that can be used and manipulated throughout your PHP script. They are created using the dollar sign ($
) followed by the variable name. PHP is loosely typed, meaning that you don’t need to declare the data type of a variable; PHP will automatically convert the variable to the correct data type based on its value.
Syntax
$variableName = value;
Rules for Variable Names
- Must start with a dollar sign (
$
). - The first character after the dollar sign must be a letter or an underscore (
_
). - Subsequent characters can be letters, numbers, or underscores.
- Variable names are case-sensitive (
$Variable
and$variable
are different).
Examples
-
Basic Variable
<?php $name = "John"; $age = 30; echo "Name: " . $name . "<br>"; echo "Age: " . $age; ?>
Output:
Name: John Age: 30
-
Variable with Different Data Types
<?php $integer = 10; // Integer $float = 3.14; // Float $string = "Hello World"; // String $boolean = true; // Boolean echo $integer . "<br>"; echo $float . "<br>"; echo $string . "<br>"; echo $boolean ? "True" : "False"; // Using ternary operator to convert boolean to string ?>
Output:
10 3.14 Hello World True
-
Concatenation of Strings
<?php $firstName = "Jane"; $lastName = "Doe"; $fullName = $firstName . " " . $lastName; echo $fullName; ?>
Output:
Jane Doe
-
Variable Variables
PHP supports variable variables, where the name of a variable is itself stored in another variable.
<?php $varName = "greeting"; $$varName = "Hello, World!"; echo $greeting; // Outputs: Hello, World! ?>
-
Global Variables
Variables defined outside of functions are global, but to use them inside a function, you need to use the
global
keyword.<?php $globalVar = "I'm global!"; function testGlobal() { global $globalVar; echo $globalVar; } testGlobal(); // Outputs: I'm global! ?>
These examples cover basic variable usage in PHP. Let me know if you need further clarification or more advanced topics!
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.