Tutorials Logic
Tutorials Logic, IN info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Website Development
Practice
Quiz Challenge Interview Questions Certification Practice
Tools
Online Compiler JSON Formatter Regex Tester CSS Unit Converter Color Picker
Compiler Tools

PHP Data Types and Variables — string, int, bool

PHP Variables

Variables are "containers" for storing information. In PHP, a variable starts with the $ sign, followed by the name of the variable. PHP is a loosely typed language, meaning you don't need to declare the data type of a variable - PHP automatically determines the data type based on the value you assign to it.

Variables can store different types of data: numbers, strings, arrays, objects, and more. They can also hold the result of expressions. PHP has no command for declaring a variable - a variable is created the moment you first assign a value to it.

Creating Variables
<?php
$txt = "Hello World!";  // String
$x = 5;                 // Integer
$y = 10.5;              // Float
$z = true;              // Boolean
$arr = [1, 2, 3];       // Array
$empty = null;          // NULL

echo $txt;              // Output: Hello World!
echo $x;                // Output: 5
?>

Standard Rules for PHP Variable Names

  • Variable names must start with a $ sign, followed by the name of the variable.
  • The variable name must begin with a letter or the underscore character (A-Z, a-z, or _).
  • Variable names can only contain alpha-numeric characters and underscores (A-z, 0-9, and _).
  • Variable names are case-sensitive ($Age and $age are two different variables).
  • Variable names should not contain spaces. Use underscore (_) or camelCase instead.
Variable Naming Examples
<?php
// Valid variable names
$myVariable = "valid";
$_private = "valid";
$var123 = "valid";

// Invalid variable names
$2var = "invalid";     // Cannot start with a number
$my-var = "invalid";   // Cannot contain hyphen
$my var = "invalid";   // Cannot contain space

// Case-sensitive
$name = "John";
$NAME = "Doe";
echo $name;  // Output: John
echo $NAME;  // Output: Doe (different variable)
?>

PHP Data Types

PHP supports several data types, which can be categorized into scalar types, compound types, and special types. Understanding data types is crucial for writing robust PHP code.

Scalar Types
<?php
// Integer - Whole numbers
$age = 25;
$temperature = -10;

// Float - Decimal numbers
$price = 19.99;
$pi = 3.14159;

// String - Sequence of characters
$name = "John Doe";
$message = 'Hello World';

// Boolean - Represents true or false
$is_active = true;
$is_logged_in = false;

var_dump($age);         // int(25)
var_dump($price);       // float(19.99)
var_dump($name);        // string(8) "John Doe"
var_dump($is_active);   // bool(true)
?>
Compound Types
<?php
// Array - Ordered map of values
$fruits = ["apple", "banana", "cherry"];
$person = [
    "name" => "John",
    "age" => 30,
    "city" => "New York"
];

// Object - Instance of a class
class User {
    public $name;
    public $age;
    
    public function __construct($name, $age) {
        $this->name = $name;
        $this->age = $age;
    }
}

$user = new User("Alice", 25);
echo $user->name;  // Output: Alice
?>
Special Types
<?php
// NULL - Represents a variable with no value
$empty = null;
var_dump($empty);  // NULL

// Resource - Special variable holding reference to external resource
$file = fopen("test.txt", "r");
var_dump($file);    // resource(stream)
fclose($file);

// Checking for NULL
$x = null;
if (is_null($x)) {
    echo "Variable is NULL";
}

// Unset vs NULL
$var = "value";
unset($var);  // Variable no longer exists
echo $var;     // Error: Undefined variable
?>

Type Checking and Conversion

PHP provides built-in functions to check variable types and convert between types. Type checking is important for validation and debugging.

Type Checking Functions
<?php
$x = 5;
$y = "10";

// gettype() - Returns the type of a variable
echo gettype($x);  // integer
echo gettype($y);  // string

// Type checking functions
var_dump(is_int($x));       // bool(true)
var_dump(is_string($y));    // bool(true)
var_dump(is_float(3.14));   // bool(true)
var_dump(is_bool(true));    // bool(true)
var_dump(is_array([1,2]));  // bool(true)
var_dump(is_null(null));    // bool(true)

// Check if variable is set
$var = "value";
var_dump(isset($var));      // bool(true)
var_dump(isset($not_set));  // bool(false)
?>
Type Conversion
<?php
// Implicit type conversion (type juggling)
$x = "5 apples";
$y = 3;
echo $x + $y;  // Output: 8 (string converted to int)

// Explicit type casting
$str = "123";
$int = (int)$str;      // or intval($str)
$float = (float)$str;  // or floatval($str)
$bool = (bool)$str;    // or boolval($str)

var_dump($int);        // int(123)
var_dump($float);      // float(123)
var_dump($bool);       // bool(true)

// settype() - Converts variable in-place
$num = "100";
settype($num, "integer");
var_dump($num);        // int(100)

// String to number conversion
echo "10" + 5;         // 15 (string "10" becomes int 10)
echo "10.5" + 2.5;     // 13 (string "10.5" becomes float 10.5)
echo "abc" + 5;        // 5 (string "abc" becomes 0)
?>

Variable Scope

The scope of a variable is the context within which it is defined. In PHP, variables have different scopes depending on where they are declared. PHP has four different variable scopes: local, global, static, and parameter.

Local vs Global Scope
<?php
$x = 5;  // Global scope

function testScope() {
    // Using global keyword to access global variable
    global $x;
    echo $x;  // Output: 5
    
    // Local variable (only accessible inside function)
    $y = 10;
    echo $y;  // Output: 10
}

testScope();

// Cannot access $y outside the function
echo $y;  // Error: Undefined variable

// Alternative: $GLOBALS array
function testGlobals() {
    echo $GLOBALS['x'];  // Output: 5
}
?>
Static Variables
<?php
// Static variable - retains its value between function calls
function counter() {
    static $count = 0;
    $count++;
    echo $count . "
"; } counter(); // Output: 1 counter(); // Output: 2 counter(); // Output: 3 // Without static, counter would always start at 0 function regularCounter() { $count = 0; $count++; echo $count . "
"; } regularCounter(); // Output: 1 regularCounter(); // Output: 1 regularCounter(); // Output: 1 ?>
Parameter Scope
<?php
// Function parameters are local to the function
function greet($name) {
    echo "Hello, $name!";
}

greet("John");  // Output: Hello, John!

// Parameters can have default values
function calculate($a, $b = 10) {
    return $a + $b;
}

echo calculate(5);      // Output: 15
echo calculate(5, 20);  // Output: 25

// Pass by reference (modifies original variable)
function addOne(&$num) {
    $num++;
}

$value = 5;
addOne($value);
echo $value;  // Output: 6
?>

Superglobals

PHP provides several built-in superglobal variables that are always accessible from any scope. These include $_GET, $_POST, $_REQUEST, $_SERVER, $_SESSION, $_COOKIE, $_FILES, and $GLOBALS.

Common Superglobals
<?php
// $_GET - Data from URL query string
// URL: example.com?name=John&age=25
echo $_GET['name'];  // John
echo $_GET['age'];   // 25

// $_POST - Data from HTML form POST method
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = $_POST['username'];
}

// $_SERVER - Server and execution environment
echo $_SERVER['PHP_SELF'];      // Current script path
echo $_SERVER['REQUEST_METHOD']; // GET, POST, etc.
echo $_SERVER['HTTP_HOST'];     // Host header

// $_SESSION - Session variables
session_start();
$_SESSION['user_id'] = 123;

// $GLOBALS - Access all global variables
$x = 10;
echo $GLOBALS['x'];  // 10
?>

Variable Variables

PHP allows you to use variable variables, which means you can use the value of one variable as the name of another variable. This is a powerful feature but should be used with caution as it can make code harder to read and debug.

Variable Variables
<?php
$a = 'hello';
$$a = 'world';

echo $a;      // Output: hello
echo $hello;  // Output: world

// Practical example
$colors = ['red', 'green', 'blue'];
$property = 'colors';

// Access array using variable variable
foreach ($$property as $color) {
    echo $color . "
"; } // Output: // red // green // blue ?>

Constants

Constants are like variables except that once defined, they cannot be changed or undefined. Constants are global and can be accessed from any scope without using the global keyword.

Defining Constants
<?php
// Using define() function
define("PI", 3.14159);
define("SITE_NAME", "Tutorials Logic");
define("MAX_USERS", 100);

// Using const keyword (PHP 5.3+)
const MIN_AGE = 18;

// Accessing constants
echo PI;           // 3.14159
echo SITE_NAME;    // Tutorials Logic

// Constants are case-sensitive by default
define("GREETING", "Hello", true);  // Case-insensitive
echo greeting;     // Hello (works due to case-insensitive)

// Magic constants (change based on context)
echo __LINE__;     // Current line number
echo __FILE__;     // Full path of file
echo __DIR__;      // Directory of file
echo __FUNCTION__; // Function name
echo __CLASS__;    // Class name
echo __METHOD__;   // Class method name
echo __NAMESPACE__; // Namespace name
?>
Key Takeaways
  • PHP is dynamically typed - variables automatically take the type of the value assigned.
  • Use gettype() to check a variable's type and settype() to convert it.
  • PHP has 8 primitive types: int, float, string, bool, array, object, null, and resource.
  • Variable names start with $ and are case-sensitive - $Age and $age are different variables.
  • Use var_dump() for debugging - it shows both the type and value of a variable.
  • Type juggling (automatic type conversion) can cause unexpected behavior - use strict comparison (===) to avoid it.
  • Global variables must be declared with the global keyword inside functions to access them.
  • Static variables retain their value between function calls - useful for counters and state.
  • Constants cannot be changed once defined - use define() or const keyword.
  • Superglobals like $_GET, $_POST, and $_SERVER are always accessible from any scope.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.