ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

PHP Tutorial• 7 min read

Variables, Data Types & Scope

Dynamic typing, type declarations, and variable scoping rules

PHP variables always begin with a dollar sign ($) followed by the variable name. PHP is dynamically typed, but modern PHP 7 and 8 provide powerful scalar type declarations.

Variable Rules and Core Types

Variables are case-sensitive: $color, $Color, and $COLOR represent three completely distinct storage slots.

Primary data types include String, Integer, Float, Boolean, Array, Object, Callable, and NULL.

Variable scope in PHP includes local, global, and static. Functions have isolated variable scope by default unless accessed via the global keyword or the $GLOBALS superglobal array.

Variables and Type Casting
<?php
  $user = "Elena Vance";
  $age = 29;               // Integer
  $rating = 4.95;          // Float
  $isSubscribed = true;    // Boolean

  // Type inspection and formatted output
  printf("%s has an account rating of %.2f (Status: %s)\n", 
    $user, 
    $rating, 
    $isSubscribed ? "Active" : "Inactive"
  );

  // Static variable retains state between function calls
  function trackVisits() {
    static $count = 0;
    $count++;
    return $count;
  }
?>
Static variables preserve their values across multiple calls within the same execution cycle.
TypeExample LiteralDescription
string"Hello Codexia"Text enclosed in single or double quotes
int42, -100Whole numbers without decimal points
float3.14159Numbers with floating fractional points
booltrue / falseBinary truth values (case-insensitive)
nullnullSpecial type representing a variable with no value
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

Which symbol MUST precede all variable names in PHP?