Codeskill

Learn to code, step by step

Variables and Data Types in PHP: A Beginner’s Guide

Time to cover PHP variables and data types. How you store information and what kinds of values a variable can hold.

What are variables?

Variables store information that can change as your script runs. Every PHP variable name starts with a dollar sign $:

<?php
$name = "Charlie";
$age = 30;
$isDeveloper = true;
?>

Here, $name, $age, and $isDeveloper hold values you can update anywhere in the script.

PHP data types

Data types define what kind of value a variable holds. PHP is dynamically typed – it figures out the type from the value you assign – but you still need to know what each type is for.

1. String

Strings are text. Wrap them in single ' or double " quotes:

<?php
$greeting = "Hello, world!";
$answer = '42 is the "answer"';
?>

2. Integer

Integers are whole numbers between -2,147,483,648 and 2,147,483,647:

<?php
$year = 2021;
?>

3. Float (or double)

Floats are numbers with a decimal point, or numbers in exponential form:

<?php
$price = 10.99;
$scientific = 0.123E2;
?>

4. Boolean

A boolean is either TRUE or FALSE – essentially yes or no:

<?php
$isLoggedIn = true;
$isAdmin = false;
?>

5. Array

Arrays store multiple values in one variable:

<?php
$colors = array("Red", "Green", "Blue");
echo $colors[0]; // Outputs 'Red'
?>

6. Object

Objects hold data and the methods to work with it. In PHP, objects are instances of classes you define:

<?php
class Car {
    function Car() {
        $this->model = "VW";
    }
}
$herbie = new Car();
echo $herbie->model; // Outputs 'VW'
?>

7. NULL

NULL means a variable has been declared but holds no value:

<?php
$nothing = NULL;
?>

Declaring variables in PHP

Assign a value to a name and PHP handles the rest – no type declaration needed:

<?php
$text = "This is PHP"; // A string
$number = 100;        // An integer
$float = 10.5;        // A floating point number
$boolean = true;      // A boolean
?>

Variable scope

Where you declare a variable determines where you can use it:

  • Global scope: Variables declared outside a function. Accessible outside functions only.
  • Local scope: Variables declared inside a function. Accessible inside that function only.
  • Static variables: Normally, local variables are destroyed when a function finishes. Use the static keyword to keep a variable alive between calls.
<?php
function testFunction() {
    static $x = 0;
    echo $x;
    $x++;
}
testFunction(); // Outputs 0
testFunction(); // Outputs 1
testFunction(); // Outputs 2
?>

Concatenating strings

Join strings with the . operator:

<?php
$firstPart = "PHP is ";
$secondPart = "awesome!";
$wholeSentence = $firstPart . $secondPart;
echo $wholeSentence; // Outputs 'PHP is awesome!'
?>

Variables and data types are the foundation of every PHP script. Next up: control structures – how to make your code branch and loop based on conditions.

PreviousPHP Syntax: The Basics of Writing PHP Scripts