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 (
$Variableand$variableare 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
globalkeyword.<?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!
Written by Shaikh Abdul Shahid
A Full-Stack Developer with experience in PHP, Laravel, JavaScript, and React.
Founder of Online Learner, sharing practical knowledge and programming tutorials.
Building and maintaining real-world web applications since 2017.
Your Feedback
Help us improve by sharing your thoughts
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
