Variables and Data Types
One of the first things to understand when learning any programming language are variables and data types.
Variables
In PHP, variables are declared with a dollar sign $
followed by the variable's name. PHP is a loosely typed language, which means that you don't have to declare the data type of a variable when you create one. Here's an example:
<?php
$name = "Alice"; // This is a string.
$age = 25; // This is an integer.
$weight = 65.5; // This is a float.
$isStudent = true; // This is a boolean.
?>
Data Types
PHP supports several data types, which define what kind of data a variable can hold:
String: A sequence of characters, like "Hello, World!". Strings are defined by enclosing the text in quotes:
<?php $string = "Hello, World!"; echo $string; // Outputs: Hello, World! ?>
Integer: A non-decimal number. Integers can be positive or negative:
<?php $integer = 42; echo $integer; // Outputs: 42 ?>
Float (or double): A number with a decimal point or a number in exponential form:
<?php $float = 3.14; echo $float; // Outputs: 3.14 ?>
Boolean: Represents two possible states:
TRUE
orFALSE
:<?php $boolean = true; echo $boolean; // Outputs: 1 (for TRUE) ?>
Array: An ordered map (a type of data structure that pairs keys with values):
<?php $array = array("Alice", "Bob", "Charlie"); print_r($array); // Outputs: Array ( [0] => Alice [1] => Bob [2] => Charlie ) ?>
Object: Instances of classes, which PHP allows you to create so that you can use objects to manage and organize your code (discussed in detail in a later section):
<?php class Car { function Car() { $this->model = "VW"; } } $herbie = new Car(); // create an object echo $herbie->model; // show object properties ?>
NULL: A special data type representing a variable with no value. A variable of data type NULL is a variable that has no value assigned to it:
<?php $var = NULL; var_dump($var); // Outputs: NULL ?>
Last updated