Brad Traversy PHP Crash Course

Get the source files from here.

Variables & Data Types


PHP Data Types



Variable Rules



Working with variables

<?php

$name = 'Brad'; // string; can be single or double quotes
$age = 40; // Integer
$has_kids = true; // Boolean
$cash_on_hand = 10.55; // Float

var_dump($name);
echo '<br>';
var_dump($age);
echo '<br>';
var_dump($has_kids);
echo '<br>';
var_dump($cash_on_hand);

echo '<br><br>';
// Double quotes are used to add variables to strings
echo "$name is $age years old and has $cash_on_hand dollars to his name.";
echo '<br><br>';
// It's common to use curly braces so the variables are more apparent
echo "${name} is ${age} years old and has ${cash_on_hand} dollars to his name.";
echo '<br><br>';
// Concatenation is achieved with a 'period'. Single quotes can be used this way
echo '<h3>' . $name . ' is ' . $age . ' years old and has ' . $cash_on_hand . ' dollars to his name.</h3>';

?>

Result

string(4) "Brad"
int(40)
bool(true)
float(10.55)

Brad is 40 years old and has 10.55 dollars to his name.

Brad is 40 years old and has 10.55 dollars to his name.

Brad is 40 years old and has 10.55 dollars to his name.

Arithmetic Operators

<?php

echo 5 + 5; // Addition
echo '<br>';
echo 10 - 6; // Subtraction
echo '<br>';
echo 5 * 10; // Multiplication
echo '<br>';
echo 10 / 2; // Division
echo '<br>';
echo 10 % 3; // Modulus

?>

Result

10
4
50
5
1

Constants

<?php

define('HOST', 'localhost');
define('USER', 'root');

var_dump(HOST);
echo '<br>';
var_dump(USER);

?>

Result

string(9) "localhost"
string(4) "root"