Labs ICT
โญ Pro Login

Variables

Variables in PHP always start with a dollar sign. It's the first thing everyone notices. $name, $age, $total_price โ€” that dollar sign is how PHP knows you're talking about a variable and not a function or keyword.

You don't need to declare a variable's type in PHP. Just assign a value and PHP figures out the type on its own. This is called loose typing, and it makes PHP incredibly flexible.


<?php
$name = "Bilal";
$age = 25;
$price = 19.99;
$is_active = true;

echo $name;
?>
    
Try it Yourself โ†’

Naming Rules

PHP variable names follow a few simple rules. They must start with a letter or underscore, followed by any number of letters, numbers, or underscores. They are case-sensitive, so $myVar and $myvar are two different things. And variable names should be descriptive โ€” $user_email is way better than $x.

  • Valid: $firstName, $_count, $user2, $total_amount
  • Invalid: $2names (starts with a number), $my-var (hyphens not allowed), $first name (spaces not allowed)

Variable Scope

Scope determines where a variable can be accessed. In PHP, variables defined outside functions are global and can't be accessed inside functions by default. Variables defined inside functions are local and stay inside the function.


<?php
$site_name = "LabsICT";  // global scope

function showSite() {
  $local_msg = "Inside the function";  // local scope
  echo $site_name;  // error โ€” $site_name is not accessible here
}

showSite();
?>
    

To access a global variable inside a function, use the global keyword:


<?php
$site_name = "LabsICT";

function showSite() {
  global $site_name;
  echo $site_name;
}

showSite();
?>
    

Assigning Values

Assignment is straightforward with the = operator. You can also chain assignments:


<?php
$a = $b = $c = 10;
echo $a;  // 10
echo $b;  // 10
echo $c;  // 10
?>
    

๐Ÿงช Quick Quiz

What symbol must precede all PHP variable names?