PHP's variable handling is one of the foundational aspects of the language. We'll break down the core components and explore each with examples.
In PHP, variables start with a `$` symbol, are case-sensitive, and can't start with a number.
Example:
$name = "John";
$Age = 25;
$city_1 = "London";
PHP is a loosely typed language, which means you don’t declare a data type when you create a variable. PHP determines the type at runtime.
Example:
$int = 123; // Integer
$float = 12.3; // Float
$string = "hello"; // String
$array = [1,2,3]; // Array
$bool = true; // Boolean
$nullvar = null; // NULL
PHP has three variable scopes:
Example:
$globalVar = "I am global!";
function test() {
$localVar = "I am local!";
global $globalVar;
echo $globalVar; // Outputs: I am global!
static $staticVar = 0;
$staticVar++;
echo $staticVar; // Outputs: 1 on first call, 2 on second call, and so on
}
test();
PHP offers several predefined arrays known as superglobals, like `$_GET`, `$_POST`, `$_SESSION`, `$_COOKIE`, `$_FILES`, `$_ENV`, `$_REQUEST`, `$_SERVER`. Example (Using `$_GET`):
// Assuming URL is http://yourdomain.com/index.php?name=John
echo $_GET['name']; // Outputs: John
There are functions in PHP dedicated to handling variables. Some key ones include:
Example:
$var = "Hello";
echo isset($var); // Outputs: 1 (true)
$var2 = "";
echo empty($var2); // Outputs: 1 (true)
$var3 = [1, 2, 3];
echo is_array($var3); // Outputs: 1 (true)
unset($var);
echo isset($var); // Outputs nothing (false)
echo gettype($var3); // Outputs: array
You can use the value of one variable to determine the name of another variable.
Example:
$a = "hello";
$$a = "world"; // Equivalent to $hello = "world";
echo $hello; // Outputs: world
Constants are like variables, but once they are defined, they can't be changed or undefined.
Example:
define("GREETING", "Hello, world!");
echo GREETING; // Outputs: Hello, world!
UPCET Exam
Click Here
SAAT Exam
Click Here
MHT CET Exam
Click Here
IPU CET Exam
Click Here
KCET Exam
Click Here
COMEDK UG Exam
Click Here
VITEEE Exam
Click Here
BITSAT
Click Here
DSAT: Dayanand Sagar Admission Test
Click Here
Career In Animation in india
Click Here
Merchant Navy Courses in india
Click Here
Interior Design Career in india
Click Here
UGC NET Exam
Click Here
B. Ed Exam
Click Here
AFCAT - Air Force Common Admission Test
Click Here
GATE Exam
Click Here
Joint Entrance Examination (JEE)
Click Here
Common Admission Test (CAT)
Click Here
CDS - Combined Defence Services Exam
Click Here