Beginner Fundamentals
PHP Variables
Variables store data that your program can use and change. In PHP, every variable name starts with a dollar sign $.
Declaring variables
You create a variable simply by assigning a value to it.
<?php
$name = "Alice";
$age = 30;
$price = 9.99;
Dynamic typing
PHP decides the type automatically based on the value. The same variable can hold different types over time.
<?php
$data = "text"; // string
$data = 42; // now an integer
Naming rules
- Must start with
$followed by a letter or underscore. - Can contain letters, numbers, and underscores.
- Cannot start with a number.
- Names are case sensitive.
<?php
$user_name = "valid";
$_count = "valid";
// $2cool would be invalid
Basic scope
A variable created inside a function is local to that function. A variable outside is global and not visible inside functions by default.
<?php
$message = "outside";
function show() {
// $message is not available here
$local = "inside";
echo $local;
}
show();