Refresh
this page because I am probably still making changes
to it.
PHP syntax is very similar to that of other languages, but
of course there are some small differences. We'll start to
take a look at the PHP syntax in this lesson by talking about
variables, constants, and the different data types that PHP
has.
Resources
The following references from the PHP Manual will be helpful:
Before doing this lesson, it's recommended that you
have already gone through the Intro
to PHP lesson.. It is also assumed that you're
already familiar with HTML and the basics of at least one other
programming language.
Basic Syntax
We already discussed PHP tags or blocks in the
previous tutorial. You can review that content from the PHP
Manual if you wish:
As you learn PHP, you're going to need to display output
or display the contents of variables and results of expressions.
You have several options available, depending on what you'd like
to do:
The echo Statement
The echo statement displays output on the page
in the location where the PHP script is.
Notice that the output from the first echo function is not inside
any HTML element. Obviously this would be back practice, all inline content should
be enclosed inside a block element, but this is just a demonstration.
The echo function can be used with or without parentheses, although
note that adding parentheses just adds them to the expression itself.
Ever see those people that do things like ((x * y) + 2) when you could
have just written x * y + 2 ? It's the same thing: the parentheses are unnecessary
and can in fact make the code less readable rather than more readable.
With brackets, the code would have looked like this:
<?php
echo("This is some text");
echo("<p>This is a paragraph.</p>");
<?>
The print Statement
The print statement can also be used with or without parentheses
and it is also a language construct. The print statement
works exactly like echo except that print returns the
integer value 1, so you can use it in expressions if needed.
print also coerces non-string values into strings when they
are printed. The echo statements
above as print:
<?php
print("This is some text"); // ignoring return value
print "<p>This is a paragraph.</p>"; // without parentheses
?>
The print statement is slightly slower than echo,
so you should be using echo unless you specifically need the return
value from print. Also, print can only accept a single argument,
whereas echo can accept multiple arguments, although we rarely pass it more
than one, anyway.
The printf Function
The printf() function works very similarly to the printf() function in the
Java language: it uses format specifiers inside a format string to print
formatted data. The documentation link above contains a list of the various
format specifier codes (if you're familiar with the codes in Java, you'll
notice there's a LOT more in PHP!) Also, unlike the Java version, printf()
will return an integer representing the number of characters that will
be printed.
The var_dump() function is useful for testing and debugging: it displays
information about the arguments you pass into it (you can pass more than
one thing into var_dump(), just separate the arguments with a comma).
What gets displayed depends on the argument. For example, if the argument
is a variable, it will display the type and value:
<p>
<?php
$foo = "bar";
var_dump($foo);
?>
</p>
The above code will output
string(3) "bar"
in a paragraph element.
For arrays, you'll see each element and its index. We'll see examples of
this when we learn about arrays.
Others
There are a couple of other functions you might find useful that
you can explore on your own:
PHP follows many of the same rules for identifiers and variables that you're
probably already familiar with!
Identifiers in PHP follow rules that are similar to other languages:
identifiers must begin with a letter or underscore
identifiers may contain only letters, numbers,
the underscore character
and other ASCII characters from 127 to 255.
identifiers are case-sensitive
identifiers can't contain spaces
identifiers can't be the same as any PHP keyword
Variables in PHP follow the rules above, and must start with a dollar-sign $.
Because PHP is weakly-typed, you don't have to explicitly declare variables in PHP,
although you can using the following syntax:
$varname = defaultValue;
As you saw in the previous tutorial, you can display an expression's
result using the PHP echo statement:
In addition to variables, you'll probably want to use constants in your
PHP code. Constants are declared using the define() function:
define("HST_RATE", .13);
The statement above defines a constant called PST_RATE with a value of .08.
You use the constant in your code just like you would in any other language:
$pstTotal = HST_RATE * $subTotal;
You can also define a constant using the const keyword:
const HST_RATE = .13;
The primary difference between define() and const
is that define() defines the constant at runtime and const defines the
constant at compile time. This means that you can use an expression as your
constant name when you use define(), and you can also define constants while
the program is running:
$taxType = array("PST", "GST", "HST");
$taxRates = array(.07, .06, .13);
for ($i = 0; $i < count($taxType); $i++) {
define($taxType[$i]."_RATE", $taxRates[$i]); // . is the concatenation operator
}
You can't do this kind of thing with the const keyword: you can't
use an expression to create the constant name (e.g. $taxType[$i]."_RATE")
and you can't define a constant while the program is running (e.g. inside the
loop; using const, you can only define a constant outside of any executing
function).
When trying to decide which to use, remember that if your constant name
is an expression or you want the constant defined at runtime, use define(),
otherwise you can use const.
<?php
define("GREETING", "Hello, ". $userName ."!"); // can use const, just wanted to show an example
const MULITPLIER = 5;
echo GREETING;
$number = 5;
echo $number * MULTIPLIER;
?>
Remember, you can also display the contents of a variable or expression
using the echo tag:
Data types in PHP can be divided into three categories: scalars, compound
data types, and special data types. All of these types are technically
primitive types.
Scalars
Scalars contain a single piece of information (this is just a regular
variable in other languages). Scalars can be bool, int,
float, or string.
bool
The bool type is PHP's Boolean type and can be given a value of
true or false. Alternatively, PHP supports standard "truthy" and "falsy"
values. Truthy values are non-boolean values that are
considered true and falsy values are non-boolean values
that are considered false
Truthy Values:
The keyword true in any case e.g. TRUE
and True are acceptable.
Any other value that is not a falsy value is a truthy value.
Falsy Values:
The keyword false in any case e.g. FALSE
and False are acceptable.
The integer values 0 and -0, the floating point values 0.0
and -0.0, and the string value "0".
Is Wendi fun? 1
Is Wendi old? 1
Is Wendi a PITA? .
When you output a bool variable value using echo or print, or when
using string interpolation, it will
convert the bool value to a string value.
That means a "true" value prints "1" and a "false" value
prints an empty string ("").
int
The integer type int is similar to integers in other languages,
as it holds any positive or negative whole number. The size of an int variable
in PHP is PHP_INT_SIZE and its value is platform-specific. The minimum and
maximum integer values permitted in PHP are defined by the constants PHP_INT_MIN
and PHP_INT_MAX. You can read more about these three constants in the
PHP Manual's Predefined
Constants
In PHP 7.4 and higher, if an integer literal is
large, you can use the _ underscore
character to separate digits without changing the meaning of the number:
$studentIdNum = 123_456_789;
If you're interested in working with binary, hexadecimal, or octal numbers, be
sure to check out the PHP Manual page for the int type - the link is in the box up above.
Note that when a bool is converted to an int,
a false value is converted to 0 and a true value
is converted to 1.
float
The floating point type float represents numbers with a decimal
part, even if that decimal part is 0 (e.g. 5.2, -5.2, 5.0, and 0.0 are all floating point
numbers. PHP floating point numbers follow the IEEE 745 standard.
Numeric literals can also be written using exponential notation:
Note that when you cast a float into an int,
the decimal portion is removed, the value is not rounded, which is how
most other languages cast floats to ints:
The string type includes literals enclosed within "double quotes" and
'single quotes'.
As you can see in the documentation, there are a series of
escape sequences you can use inside string literals, much
like in other languages. For example, the sequence
\n adds a newline and \\ adds
a backslash. Note that the newline, when used in HTML output,
only adds a newline to the source, not the actual page.
To add a newline to a page, put your content inside a block
element, or use a <br> tag if the use is appropriate.
String Interpolation
PHP has some neat features when it comes to printing string
epxresions. For example:
<p>
<?php
$n = 2;
$d = 3;
echo $n."/".$d." is a fraction.";
?>
</p>
In PHP, the dot or period ( . ) is the concatenation operator.
So this echo statement concatenates the values of $n and $d with a
forward slash / between them and then conatenates that to the
literal " is a fraction.". The output is:
2/3 is a fraction.
The double-quotes works differently in PHP: it will parse or
expand variables and some kinds of expresions. So you can write
the code above as:
<p>
<?php
$n = 2;
$d = 3;
echo "$n/$d is a fraction.";
?>
</p>
This code will produce the exact same output as the previous example.
You can also use some commen escape sequences like \n (newline).
If you print with single-quotes, PHP will not interpolate or parse
variables and expressions, including escape sequences:
<p>
<?php
$n = 2;
$d = 3;
echo '$n/$d is a fraction.\n';
?>
</p>
This code will output:
$n/$d is a fraction.\n
Knowing how PHP interpolates strings can come in handy when you
want to print complex expressions. You can find more details
and some additional syntax in the
PHP Manual page on strings.
Compound Types
Compound data types include arrays, objects, callables, and iterables.
They're called compound types because they
do more than just hold a single value: they can hold many values and/or even hold functions.
Objects contain properties or data members and functions or
methods. Objects model real-life objects and can interact with other objects
and other parts of the application. We'll learn about classes
and objects in a later lesson and we'll use lots of built-in PHP objects
throughout these tutorials.
Callables are functions or methods that can be
passed to other functions, methods, or classes. We'll learn more about
functions and callables in a later lesson.
Iterables are new to PHP and allow you to iterate more
easily and efficiently through arrays and objects.
Special Data Types
This category includes the special type null.
It has a single value, which is null.
The null value is used when you want to empty or unset a variable or resource,
or initialize an object variable to an "empty" value (the equivalent of a 0
for a numeric value).
There is also a constant in PHP called NULL,
which contains the value null. It can be confusing,
but remember that null is a literal value and
NULL is a contant name.
This also includes the type resource. The resource type is for
storing references to resources such as files or databases. We'll learn about
the resource type when we start learning about
working with databases.
Type Conversions
Because PHP is weakly-typed, all of the following statements are valid:
Notice that when $myValue is assigned a string, the type is string.
When $myValue is assigned the integer value 5, $myValue is an int.
When $myValue is assigned a floating point number 2.5, $myValue is a float.
A variable's data type is dependent on the type of its contents.
If you need to, you can explicitly cast a value into another type: