Variables and Data Types

In this lesson, you'll learn how to store information in variables and work with different types of data. PHP is a dynamically-typed language, which means you don't need to declare variable types - PHP figures them out automatically!

What You'll Learn

  • How to declare and use variables in PHP
  • The different data types in PHP
  • How to work with strings, numbers, and booleans
  • Type checking and conversion
  • Variable naming conventions

Declaring Variables

In PHP, all variables start with a dollar sign $. You don't need to declare the type - PHP automatically determines it based on the value:

<?php

// Variables are created when you assign a value
$name = "Alice";
$age = 25;
$isStudent = true;

echo "Name: $name\n";
echo "Age: $age\n";
echo "Is student: " . ($isStudent ? "yes" : "no") . "\n";

Variable Naming Rules

  • Must start with a letter or underscore
  • Can contain letters, numbers, and underscores
  • Case-sensitive ($name and $Name are different)
  • Cannot start with a number
<?php

// Valid variable names
$firstName = "John";
$last_name = "Doe";
$age2 = 30;
$_temp = "temporary";

echo "Full name: $firstName $last_name\n";
echo "Age: $age2\n";

Basic Data Types

PHP supports several built-in data types. Let's explore the most common ones:

Strings

Strings represent text. PHP offers three ways to create strings:

<?php

// Double quotes - interprets variables and escape sequences
$name = "PHP";
$greeting = "Hello, $name!\n";
echo $greeting;

// Single quotes - literal strings (faster, no interpretation)
$literal = 'Hello, $name!\n'; // Won't replace $name
echo $literal . "\n";

// Concatenation with the dot operator
$message = "Welcome to " . $name . " programming!\n";
echo $message;

// String functions
$text = "learning php";
echo "Uppercase: " . strtoupper($text) . "\n";
echo "Length: " . strlen($text) . "\n";

Best Practice: Use double quotes when you need variable interpolation, single quotes for literal strings.

Numbers

PHP has two main numeric types: integers and floats:

<?php

// Integers (whole numbers)
$count = 42;
$negative = -10;
echo "Count: $count\n";
echo "Negative: $negative\n";

// Floats (decimal numbers)
$price = 19.99;
$pi = 3.14159;
echo "Price: $price\n";
echo "Pi: $pi\n";

// Mathematical operations
$sum = 10 + 5;
$difference = 10 - 5;
$product = 10 * 5;
$quotient = 10 / 5;
$remainder = 10 % 3;
$power = 2 ** 3; // 2 to the power of 3

echo "Sum: $sum\n";
echo "Difference: $difference\n";
echo "Product: $product\n";
echo "Quotient: $quotient\n";
echo "Remainder: $remainder\n";
echo "Power: $power\n";

Booleans

Booleans represent true or false values:

<?php

$isActive = true;
$isComplete = false;

echo "Is active: ";
var_dump($isActive);

echo "Is complete: ";
var_dump($isComplete);

// Comparison operations return booleans
echo "5 > 3: ";
var_dump(5 > 3);

echo "5 < 3: ";
var_dump(5 < 3);

echo "5 === 5: ";
var_dump(5 === 5);

Note: Use var_dump() to see the actual boolean value. echo true prints "1" and echo false prints nothing.

NULL

NULL represents a variable with no value:

<?php

$empty = null;
echo "Empty variable: ";
var_dump($empty);

// Unset variables are also null
$notSet;
echo "Not set variable: ";
var_dump($notSet);

Type Checking

You can check the type of a variable using various functions:

<?php

$string = "Hello";
$number = 42;
$float = 3.14;
$bool = true;
$nothing = null;

// gettype() returns the type as a string
echo "String type: " . gettype($string) . "\n";
echo "Number type: " . gettype($number) . "\n";
echo "Float type: " . gettype($float) . "\n";
echo "Bool type: " . gettype($bool) . "\n";
echo "Null type: " . gettype($nothing) . "\n";

// Specific type checking functions
echo "Is string? " . (is_string($string) ? "yes" : "no") . "\n";
echo "Is int? " . (is_int($number) ? "yes" : "no") . "\n";
echo "Is float? " . (is_float($float) ? "yes" : "no") . "\n";
echo "Is bool? " . (is_bool($bool) ? "yes" : "no") . "\n";
echo "Is null? " . (is_null($nothing) ? "yes" : "no") . "\n";

Type Conversion

PHP automatically converts types when needed (type juggling), but you can also manually convert types:

<?php

// Automatic type conversion
$result = "5" + 3; // String "5" becomes integer 5
echo "String + number: $result\n";

$concat = "5" . 3; // Number 3 becomes string "3"
echo "String concatenation: $concat\n";

// Manual type casting
$strNumber = "42";
$num = (int)$strNumber;
echo "String to int: $num (type: " . gettype($num) . ")\n";

$number = 42;
$str = (string)$number;
echo "Int to string: $str (type: " . gettype($str) . ")\n";

// Using conversion functions
$value = "123.45";
echo "intval: " . intval($value) . "\n";
echo "floatval: " . floatval($value) . "\n";
echo "strval: " . strval(123) . "\n";

Variable Variables

PHP has a unique feature called "variable variables" where you can use the value of one variable as the name of another:

<?php

$varName = "greeting";
$$varName = "Hello, World!"; // Creates $greeting

echo $greeting . "\n"; // Outputs: Hello, World!
echo $$varName . "\n"; // Also outputs: Hello, World!

Try It Yourself

Practice what you've learned! Create variables and try these exercises:

<?php

// 1. Create a variable for your name (string)
$myName = "Your Name";
echo "My name is: $myName\n";

// 2. Create a variable for your age (integer)
$myAge = 25;
echo "I am $myAge years old\n";

// 3. Calculate your birth year (approximately)
$currentYear = 2024;
$birthYear = $currentYear - $myAge;
echo "I was born in: $birthYear\n";

// 4. Create a boolean for whether you like coding
$likesCoding = true;
echo "Likes coding: ";
var_dump($likesCoding);

// 5. Try concatenating strings
$firstName = "John";
$lastName = "Doe";
$fullName = $firstName . " " . $lastName;
echo "Full name: $fullName\n";

// Try modifying the values and adding your own variables!

Key Takeaways

  • PHP variables start with $ and are dynamically typed
  • Use double quotes for strings with variables, single quotes for literals
  • PHP has integers, floats, strings, booleans, and null types
  • Concatenate strings with the dot (.) operator
  • Use gettype() or is_*() functions to check types
  • PHP automatically converts types when needed (type juggling)
  • Variable names are case-sensitive

Next Steps

Now that you understand variables and data types, you're ready to learn about functions - reusable blocks of code that make your programs more organized and powerful!

Pro Tip: PHP's dynamic typing is convenient, but be aware of automatic type conversions. Use strict comparison (===) instead of loose comparison (==) when you need to check both value and type. Experiment with different type conversions to understand how PHP handles them.

Variables and Data Types | LearningPHP.org