Heya! In this course, we'll master PHP, a programming language that's used by millions of websites.
Let's hit the ground running and check out what this little PHP script does.
<?php echo "Welcome, friend!"; ?>
//Output Below
Ah! In this lesson, we'll find out what we just did here.
PHP can do tons of things, making it a great choice for almost any website.
What might these things include?
Yes! That's why even big companies like Facebook and Tesla use PHP.
PHP programs, or scripts as they're called, start with an opening tag and end with a closing tag.
Let's see the two tags in a script.
<?php echo "Welcome, friend!"; ?>
and
That's right! These tags form the beginning and the end of every script.
Do you remember the special word we used to display "Welcome, friend!"
?
<?php echo "Welcome, friend!"; ?>
//Output Below
That's it! The echo
keyword displays, or prints, the plain text we put in the quotation marks after it.
Also, there's a special symbol at the end of every line.
What kind of symbol was that again?
<?php echo "Welcome, friend!"; ?>
//Output Below
Yes! The semicolon tells the server that it can move to the next line.
Apart from plain text, however, PHP can also handle numbers and do math with them.
<?php echo 2 * 4; ?>
//Output Below
Magical! The *
sign is an operator that multiplies two numbers. The +
operator unsurprisingly, will add two numbers.
Psst: numbers have no quotation marks around them.
To create some more complex scripts, we need a way to remember information. So-called variables help us do just that.
<?php $name = "Slim Shady"; echo $name; ?>
//Output Below
Great! Variables start with a $
sign and have a name. We can pass them information using the =
sign.
Comments are lines that can help us understand a script. We introduce them with two slashes.
<?php // Create a variable and display its content: $name = "Slim Shady"; echo $name; ?>
//Output Below
Perfect! When a line starts with //
, it's ignored by the server.
Now, PHP is a so-called server-side language, which makes it different from languages like JavaScript.
Why might that be?
That's it! PHP scripts run on a server, which is the computer that stores them. Only the results are delivered to browser.
When we combine PHP with HTML, we can create dynamic webpages.
<html> <body> <?php echo "Hi, I'm written in PHP"; ?> </body> </html>
//Output Below
Yay! When we open this webpage, the server processes the script and sends only the output to the browser.
If we include a PHP script in an HTML file, we need to save it with a .php
extension.
Why might that be?
Right! The .php
extension tells the server that there's PHP code in the file that it needs to process.
As we already know, variables are containers that can store information, or values to be precise.
<?php $name = "Slim Shady"; ?>
There! Now the $name
variable stores the value "Slim Shady"
.
"Slim Shady"
is a so-called string, a sequence of characters wrapped in single or double quotes.
<?php $first = 'Slim '; $second = "Shady"; echo $first, $second; ?>
//Output Below
Slim Shady
See that? It doesn't matter if we use single or double quotes, as long as we want them to be part of the string.
We can do lots of fun things with strings. For example, we can add them together.
<?php $intro = "Hi, my name is "; $name = "Slim Shady"; echo $intro . $name; ?>
//Output Below
Hi, my name is Slim Shady
Well said! The .
sign is a so-called operator that combines the values of two or more strings.
Let's talk numbers. An integer is another data type that can represent whole numbers.
<?php $number = 720; echo $number; ?>
//Output Below
720
That's right! We've stored an integer, which can be positive or negative, in $number
.
A float, or floating-point number, is a data type for numbers with a decimal point.
<?php $number = 5.28; echo $number; ?>
//Output Below
5.28
Bingo! We've stored a float in $number
. Just like integers, these values can be positive or negative.
We can use operators to do math with numbers.
Let's try and add these numbers.
<?php $number1 = 49; $number2 = 7; echo $number1 + $number2; ?>
//Output Below
56
See that? The +
sign adds the numbers together just like a regular calculator.
Psst: The -
, *
, and \
signs also work exactly as you'd expect them to.
If we want to in increase the value of a variable by, say, 10
, we can use a shortcut.
<?php $number = 16; echo $number += 10; ?>
//Output Below
26
Perfect! +=
, -=
, *=
, and /=
give the result of the operation back to the variable.
A boolean is a data type that can only be true
or false
.
Which of these might be the correct way to assign a boolean value?
<?php $boolean = true; echo $boolean; ?>
//Output Below
1
See that? When we use echo
with a true
boolean, 1 is printed. If the boolean were false
, 0
would be printed.
Finally, constants are almost like variables, except that their values are, well, constant.
<?php define("PI", 3.1415926535898); echo PI; ?>
//Output Below
3.1415926535898
Yes! We don't need the $
sign with constants and usually write their names in uppercase letters.
We can use so-called conditional statements to run a segment of a script only if a certain condition is met.
<?php if (true) { echo "Hi there!"; } ?>
//Output Below
Hi there!
Fantastic! The code in the braces of an if statement only runs if its condition has the boolean value of true
.
That's why boolean values are so much more useful than they seem to be. For example, they're the result of comparisons.
Let's try and echo
the statement here.
<?php $hour = 9; if ($hour < 12) { echo "Hello there!"; } ?>
//Output Below
Hello there!
See that? We can use >
and <
to check if a value is greater or less than another.
We can also check whether a value or variable is equal or not equal to something.
<?php $hour = 12; if ($hour == 12) echo "Equal!"; if ($hour != 1) echo "Not equal!"; ?>
//Output Below
Equal!Not equal!
Perfect! The ==
and !=
signs are the comparison operators that check if two values are the same or not.
Also, we can run code when the condition in the if statement isn't met. That's what we call an else statement.
<?php $hour = 12; if ($hour < 12) { echo "Good morning!"; } else { echo "Good afternoon!"; } ?>
//Output Below
Good afternoon!
Yes! The code in the braces of the else statement runs when the condition that comes before it returns false
.
Another set of comparison operators can check for equality and inequality at the same time.
<?php $hour = 20; if ($hour >= 18) { echo "Good evening!"; } ?>
//Output Below
Good evening!
See that? The <=
and >=
signs check if a value is greater than or equal to or less than or equal to another value.
We can also combine the else
and if
keywords to account for multiple conditions.
<?php $hour = 20; if ($hour < 12) { echo "Good morning!"; } elseif ($hour < 18) { echo "Good afternoon!"; } else { echo "Good evening!"; } ?>
//Output Below
Good evening!
Bravo! The elseif
keyword allows us to add as many conditions as we want to check for.
What if we want to test if two conditions are true at the same time, though? For that we use something called the logical and.
Which of these would satisfy what is either side of the &&
?
<?php $hour = 12; if ($hour >= 0 && $hour < 24) { echo "Triggered!"; } ?>
//Output Below
Triggered!
See that? &&
the logical and, needs both conditions met for the code inside to be executed.
When we want test if at least one condition is true, we use something called the the logical or.
Which of these would satisfy at least one condition either side of ||
?
<?php $hour = 0; if ($hour == 0 || $hour < 24) { echo "Triggered!"; } ?>
//Output Below
Triggered!
Nice. ||
the logical or operator requires only one condition to be true in the statement for the code inside to be executed.
When we want to compare a variable with many different values, switch statements might be the better option.
Let's see what happens when we give $season
a value here.
<?php $season = "Winter"; switch ($season) { case "Winter"; echo "Frozen season"; break; case "Fall"; echo "Cool season"; break; default: echo "Other season"; } ?>
//Output Below
Frozen season
See that? case
checks for a scenario, break
ends the code, and default
triggers when there are no matches.
What if we want multiple cases in a switch statement to trigger the same code? In that case we group them together.
Which of these might trigger "You're not a freshman"?
<?php $year = 3; switch($year) { case 1: echo "You're a freshman"; break; case 2: case 3: case 4: echo "You're not a freshman"; break; default: echo "Are you still in school?"; } ?>
//Output Below
You're not a freshman
See that? Cases without a break
keyword will fall through to the next break
keyword or to the end.
An array is a special kind of variable that can store multiple values in a single variable.
<?php $friends = array(); ?>
Huzzah! We just created an array with array()
, the so-called array constructor.
An empty array doesn't really serve a purpose, though. How about we give $friends
some values?
<?php $friends = array("Caroline", "Max"); ?>
Great! We can create an array with values by putting them in the parentheses of array()
.
But how can we access the contents of an array?
<?php $friends = array("Caroline", "Max"); echo $friends[0]; ?>
//Output Below
Caroline
That's it! We can access a value by putting its position in brackets after the array's name.
Psst: this position is zero-based, which means that it starts at 0
.
We can also add values to an array. Let's add something to $friends
, shall we?
<?php $friends = array("Caroline", "Max"); $friends[] = "Earl"; ?>
Nice! We can add a value by giving it to the array with brackets but without a position.
Now that we know how to add values, how might we be able to replace one?
<?php $friends = array("Caroline", "Max"); $friends[1] = "Chestnut"; var_dump($friends); ?>
//Output Below
array(2) { [0]=> string(8) "Caroline" [1]=> string(8) "Chestnut" }
Fantastic! We can replace a value by storing a new value at a position that already exists.
Psst: var_dump()
is a so-called function that displays information about a variable. It allows us to see the whole array.
We can find out the number of items in an array as well. How might we do this?
<?php $friends = array("Caroline", "Max"); echo count($friends); ?>
//Output Below
2
Sweet! We can use the count()
function to find out how many values an array has.
We can also sort an array. Let's add some more values and get $friends
in alphabetical order!
<?php $friends = array("Caroline", "Max", "Earl", "Oleg", "Han"); sort($friends); var_dump($friends); ?>
//Output Below
array(5) { [0]=> string(8) "Caroline" [1]=> string(4) "Earl" [2]=> string(3) "Han" [3]=> string(3) "Max" [4]=> string(4) "Oleg" }
Right on! The sort()
function orders the items of an array in ascending order, be they numbers or strings.
Psst: another function called rsort()
sorts an array in descending order.
Sometimes we need to repeat a task over and over again.
<?php $friends = array("Caroline", "Max", "Earl", "Oleg", "Han"); echo $friends[0] . ", "; echo $friends[1] . ", "; echo $friends[2] . ", "; echo $friends[3] . ", "; echo $friends[4]; ?>
//Output Below
Caroline, Max, Earl, Oleg, Han
Look at all these lines of code! Might a loop be more readable without repeating ourselves?
A so-called while loop runs a block of code as long as a certain condition is true
.
<?php $number = 1; while ($number < 4) { $number += 1; echo $number . ", "; } ?>
//Output Below
2, 3, 4,
Yes! This while loop increases $number
by 1 as long as it's less than 4. Once at 4, the condition turns false
and the loop stops.
A do while loop is a type of while loop that first runs the block of code then checks if the condition is true
.
<?php $number = 1; do { $number += 1; echo $number; } while ($number > 4); ?>
//Output Below
2
See that? No matter what the condition, the loop runs at least once.
Psst: notice that the do while loop ends with a semicolon.
The for loop is a very popular type of loop. It has 3 parts: the value, the condition, and a way to change the value.
<?php for ($i = 0; $i < 4; $i++) { echo $i . ", "; } ?>
//Output Below
0, 1, 2, 3, 4,
Sweet! $i
starts at 0
and increases as long as the condition is true
. Once it returns false
, the loop stops.
Psst: $i++
is an even shorter version of $i += 1
.
Now, the so-called foreach loop works only on arrays, because it goes through each of their elements.
<?php $heroes = array("Batman", "Robin", "Batgirl"); foreach ($heroes as $hero) { echo $hero . ", "; } ?>
//Output Below
Batman, Robin, Batgirl,
Nice! In every so-called iteration, the value of an element is stored in $hero
.
A function is a block of code that we can reuse whenever we want.
<?php function sayHi() { echo "Hi there!"; } ?>
Nice! We need the function
keyword, a name, and some parentheses. The code in the braces runs when we use the function.
But why didn't sayHi()
display anything? Well, that's because we need to call a function to make it run.
<?php function sayHi() { echo "Hi there!"; } sayHi(); ?>
//Output Below
Hi there!
Sweet! Whenever we want to call a function, we use its name and add parentheses at the end.
We can also pass information to functions through arguments.
<?php function sayHi($name) { echo "Hi there, $name!"; } sayHi("Joe"); ?>
//Output Below
Hi there, Joe!
See that? When we use an argument with sayHi()
, we can access it through $name
variable.
Psst: notice how we can put variable names right into a string.
In addition to performing tasks, functions can return values as well.
<?php function sum($n1, $n2) { $sum = $n1 + $n2; return $sum; } echo "1 + 7 = " . sum(1, 7); ?>
//Output Below
1 + 7 = 8
Yes! We use the return
keyword to give back a value whenever the function is called.
PHP has a lot of built-in functions as well. Some of them help us manage strings.
How might we convert a string to lowercase?
<?php echo strtolower("Here's the LOWDOWN."); ?>
//Output Below
here's the lowdown.
That's it! strtolower()
will convert any string
to lowercase.
Psst: strtoupper()
will convert strings to uppercase.
What if we want to replace characters in a string with other characters?
<?php $greeting = "Howdy y'all!" echo str_replace("y'all", "Joe", $greeting); ?>
//Output Below
Howdy Joe!
Great, right? str_replace()
takes 3 arguments: the value to replace, its replacement, and the string it's in.
Psst: notice that str_replace()
is case-sensitive.
We can get part of a string with the substr()
function.
It has 3 parts: the string, the index to start at, and the number of characters to get from there.
<?php $text = "You: a constant in the sea of variables."; echo substr($text, 0, 15); ?>
//Output Below
You: a constant
See that? We extract different parts of a string by changing the index and the number of characters to get.
We can also count the number of words in a string with a built-in function.
<?php echo str_word_count("You: a constant in the sea of variables."); ?>
//Output Below
8
There! The str_word_count()
function does the trick.
Other built-in functions handle integers and floats.
How might we round a number?
<?php echo round(1.5); ?>
//Output Below
2
Fantastic! We can round a number with the round()
function.
Now, with the explode()
function, we can spit a string into an array. It takes 2 arguments: a delimiter and a string.
<?php $game = "rock, paper, scissors"; $items = explode(", ", $game); var_dump($items); ?>
Sweet! The delimiter is the string that separates the values in the original string.
Psst: var_dump()
, of course, is also a function.