Learn to Code via Tutorials on Repl.it!

← Back to all posts
PHP Tutorial, I Guess
Th3Coder

PHP Tutorial, I Guess

Hello there!

If you're a web developer, you definitely know that:

  • HTML is used for basic website formatting
  • CSS to make the site look good
  • JavaScript to make the site responsive and working!

But there's a fourth language which I unfortunately rarely see anyone use in Replit...

PHP!

(At the time I typed this post, there are 46K HTML/CSS/JS repls but only 1.9K PHP Web Server repls!)

What is PHP for?

PHP can be used for many different things, but it's mainly used to transfer data from the user (client-side) to the server in a website!
You can learn basic PHP without prior programming knowledge, but keep in mind to use it in a website you also need to know HTML (like the example below) and JavaScript!
For instance, if the user fills in an input form, you as the website owner can see whatever the user typed!
So, let's make a simple HTML input form:

It will look as such:

So, of course, the user can submit the form but after that nothing will happen! That's because no data is sent to the server side.

For that, we use PHP!

So first things first, all PHP code must be in a .php page.
.php pages are basically .html pages that support PHP! You can code HTML and PHP in the same file!

Unfortunately though, before we learn how to send the data to the server side, we must know the basics of PHP first!
Also you'll see analogies explaining variables, arrays, etc because maybe some of you might not know what they are yet! If you already know them, feel free to skip the analogies :)
Also, here's the table of contents!

  • Table of Contents (seriously)
  • General code
    • Basics
    • Comments
    • Variables
    • Concantenation (combining strings)
    • Numeric Operations
    • Outputs
    • If conditions
    • Arrays
    • Loops
      • While loops
      • For loops
      • Foreach Loops
    • Functions
  • Website-Based PHP
    • Sending data to the server
    • Appending text to a file

Now, let's code!

Basics

PHP code starts with <?php and ends with ?>. It's generally embedded inside a HTML tag, for instance:

Note: I will skip these tags for some example codes to simplify things!

Comments

So, let's make a random code and put an unimportant text:

If you run it, PHP will get confused and show an error! That's because PHP doesn't understand what you coded.
So, how do we make PHP ignore that statement?
We use comments!
Comments are basically anything you can type that is ignored by the program!
For instance, if you type a hashtag (#) or double slash (//) before that unimportant text, PHP will simply ignore that unimportant text!

There are also multi-line comments!
So basically, PHP will ignore EVERYTHING between /* and */!

Here's an example:

Now, let's continue!

Variables

Meet Sam.
He has a smart talking cat that can remember anything. For instance, if you tell the cat to remember the number 7, it'll remember the number when you ask it again!

But first, we have to name the cat. Let's name it Banana! Great name

So Banana remembers the number 7 (of course). We can say Banana has the value of 7!
Same thing goes with variables. Here banana is the name and 7 is the value!
Typically, we can change a variable's value. For instance, we can ask Banana to remember the value 8 instead! Also we can use more cats if we want!
However, there is a special type of variables called constants where you can't change the value! We'll learn about them later :)

Variables in PHP are declared using the dollar sign ($), the variable name, equal sign (=), and value!

For example:

There are also rules about variable names in PHP, but to keep it simple I recommend you to not use special characters at all and not use numbers at the beginning :)
Also, note that almost every line of PHP code must end with a semicolon (;)! It's not like JavaScript where you can ignore semicolons and nothing will happen :)

Concantenation (combining strings)

If we add "Hello, " and "world!", we'll get "Hello, world!"
The same thing can be said with PHP! We combine strings using a period (.)! For example:

See that line $text1 = $text1." ".$text2?
I'll explain!

  • $text1 originally has a value of "I'm learning"
  • $text = $text1." " means we add a space (" ") to $text1, so now $text1 has a value of "I'm learning "!
  • And now, we add $text2 to $text1. This means now $text1 has the value of "I'm learning PHP!"

Numeric Operations

Just like many other languages, PHP uses:

  • + for addition,
  • - for substraction,
  • * for multiplication,
  • / for division,
  • % for modulo (or finding the remainder of a division), and
  • ** for exponentiation!

We can also shorten operations, for instance we can shorten $x = $x + $y to $x += $y!

Also, there also 2 extra operations we can shorten!

  • We can use $x++ instead of $x += 1.
  • We can also use $x-- instead of $x -= 1! Keep these in mind :)

Outputs

So, remember that PHP code is generally embedded inside HTML tags?

As an example, our PHP code is embedded inside <p> tags.

So, anything the PHP code outputs will be displayed inside that <p> tag!

We output using the keyword echo, for instance:

So, the rendered HTML page will be:

Keep in mind there is no space between both texts because we didn't output a space!

We can also output HTML tags using PHP, for example:

So the rendered HTML page will be:

But what if we want to add double quotes " and single quotes ' inside the text?
We use named entities!

  • Single quotes (') can be typed as &apos;
  • Double quotes (") can be typed as &quot;
  • Ampersand (&) can be typed as &amp;!
    So, we can code:

And the output will be...

Note: if we're not using PHP in a website, we don't need to embed the code inside <p> tags :)

If conditions

Basically, the if statement makes a piece of code run only if the condition is true.

Here's an example:

To be simple, $a == 3 basically tests if $a has the value of 3!

  • If $a has the value of 3, the condition will be true and code between the curly brackets ({}) will be executed!
  • However, if the value of $a is not 3, the condition will be false and the code will simply be ignored!

But there are also other operators!

OperatorsUsesExamplestrue/false
==Equal to5 == 8false
!=Not equal to6 != 4true
<Less than7 < 10true
>More than7 > 10false
<=Less than or equal12 <= 12true
>=More than or equal11 >= 8true

(Take a moment to read the table above)

We can also use the keywords elseif and else after an ifstatement, for instance:

Here's the explanation about the if, elseif, and else statements:

There are also more you can do with these statements!
Let's make a code that outputs duck if the number's between 5 and 10!

Here, we need to make a code that is executed only if the number's bigger than 5 and the number's smaller than 10!

Normally we can just use 2 if statements, but there's a way to combine it to just 1 line!
So we need 2 conditions:

  • the number's bigger than 5 ($a > 5)
  • the number's smaller than 10 ($a < 10)

We can just put both in one line and add 2 ampersands (&&) between them! Those 2 ampersands are called the and operator :)

For instance:

However, what if we want the number to be either bigger than 10 or smaller than 5?

We can use the or (||) operator this time!

We can also add an exclamation mark (!) before the condition to run the code if that condition is wrong! For example:

And the output will be...

Last but not least, we can shorten comparisons with booleans!
So booleans can have 2 values (true or false)! We can shorten their comparisons, for instance:

Arrays

For some reason, Sam wants to add his neighbors to a program!

Well, for Sam to do this, he must use 4 cats! (If you don't understand, that means you skipped the explanation in the variable part!)
That's pretty ineffective, so why not stack all that information in just 1 cat?
Yep, imagine telling the cat to remember 4 values: Grandpa, Little Timmy, My tree, and The cat over there!
So you can ask what the first value you gave was, and the cat will answer Grandpa!
That's exactly how arrays work. An array is basically a bunch of values, but they're stacked to just 1 variable!

In PHP, arrays are declared using the array() function! Here's an example:

But how do we get the information back?
Well, we use indexes!
The cat will remember:

  • Grandpa as information number 0
  • Little Timmy as information number 1
  • My tree as information number 2
  • and The cat over there as information number 3!

But wait, why does the cat count from 0?
Because that's actually how it works. Mostly.

So to access a value inside that array, we use the index inside square brackets [ ]!

We can also change the values in arrays!
For instance, we can ask the cat to change the first value we gave it!
Let's say Little Timmy changed his name to, err, Little Baby Bum.

Sam's class just had a Math test!
He wants to data his scores and his classmates' scores in a program, but using the arrays we just talked about isn't effective!
So, remember that indexes are numbers starting from 0?
Well, indexes can also be letters/strings!
We use the arrow => keyword to do this, for instance:

So now, the values are 99.9, 62.892, -56, 103, and 0!
The indexes are Sam, Sam Jr., Peter Parker, Sam Junior Junior, and The teacher! The indexes aren't numbers!
So you can ask "What is Sam's score?" and the cat will answer 99.9!

There's also a function called length, it returns the number of values in the array! For instance:

Loops

Loops basically execute a piece of code several times!
PHP has while loops, for loops, and foreach loops. What are those?

While loops

Imagine an if condition:

Here we add 1 to x if it's less than 5. But what if we want to add it multiple times until its value is 5?

We use loops!
There are several types of loops, but first we'll learn about while loops as I think they're the easiest!
For example:

If you look closely, the syntax is quite similar to if conditions! The difference is that loops repeat the code as long as the condition is true, and stops executing it if the condition is false!

Take a moment to read that sentence above again :)
The logic goes like this:

  • At first the value of $x is 0
  • Since the condition $x < 5 is true, the loop will executed.
    • The code $x++ adds 1 to $x, so now the value of $x is 1!
  • Then it checks the condition again. Since $x < 5 is still true, the loop will be executed again!
    • The value of $x is now 2!
  • And so on.
  • When the value of $x is 5, the condition $x < 5 will be false and the loop won't be executed!
  • However, the loop will keep continuing if the condition is still true!

Here's yet another really bad analogy!
Sam's Math exam was 10 PAGES LONG.
However, his goat ate the third page!
And now, he wants to output the question pages for some reason. We'll have to loop from 1 to 10, but skip 3!
So how do we do this?
We use the continue keyword!
Basically, the continue keyword skips a value and moves on to the next one!
Here's an example:

And the output is...

Again, they're all in the same line because echo doesn't make a new line for us :)
But what if instead of skipping 3 and continuing to 4, we stop the loop when we reach 3?

For that, we use yet another keyword break!
For instance:

And the output is...

There's also a variation of the while loop called the do...while loop which executes the code at least once!
So, for example, here's a normal while loop:

The output will be...

Yes, you read that right. There is no output because the condition $a > 50 is false in the first place!
But in do...while loops, something changes. Remember the code will get executed at least once, even though the condition is already false!

Even though the condition is false in the first place, the code will still be run and output:

Feel free to read this again if you don't understand :)

For loops

For loops are actually just squished while loops using the keyword for!
Here's a comparison!
WHILE LOOPS

FOR LOOPS

See this line:
for ($x = 0; $x < 5; $x++)
This line is made out of 3 parts!

  • Firstly, before we start the loop we obviously need a variable. So we have to define the variable first, here we use $x = 0!
  • Next up, we need $x < 5 which is the condition. Of course, the code will be run as long as the condition is still true!
  • Last but not least, $x++ tells the program to add 1 to x's value every single time before repeating the loop! We can also use $x--!
    Feel free to read that again if you want :)

Foreach Loops

Let's make an array!

What if we want to output all the values in the array?
We use the foreach loop!
Imagine tell the cat to loop through all the values in the array and output them!
That's how it works.
So, to use it, we use the foreach and as keywords!
For example:

See the $words as $word?

  • So firstly it will go to the first value in the array which is Neptune and call it $word!
    • Now $word has the value Neptune!
    • Then it will execute the code echo $word and output "Neptune"!
  • Then it goes to the next value in the array (umbrella) and call it $word!
    • As I said earlier, $word now has the value umbrella!
    • So the code echo $word will be executed again! It will output umbrella!
  • And so on until it reaches the last value in the array!

Feel free to read again if you haven't understood yet :)

Switch Cases

Let's make a program that turns numbers to words!

That is WAY too long, so how do we shorten it?
Well, we use switch cases!
Interestingly enough, the switch case acts (kind of) like a loop! Here's an example:

  • So firstly, we have the line switch($number).
    • This means we're checking the value of $number!
  • Then we have case 1!
    • This executes the code below if $number's value is exactly 1! Think of it like if ($number == 1)
    • We also use the keyword break just like in a loop!
  • We also have case 2 but since $number's value isn't 2, the code below is ignored!
  • Then there's case 3. Since $number's value IS 3, the code below is executed and it outputs three!

Again, feel free to read it again if you don't understand :)
Then, we also have the default keyword which executes a piece of code if none of the cases match! It's just like an else keyword :)

Functions

Fear not, THIS IS THE LAST THING WE NEED TO LEARN BEFORE WE ADVANCE TO WEBSITE-BASED PHP! Even though there are also classes and stuff, I recommend you to use JavaScript for those :)

Let's rickroll someone!

Every time we want to rickroll someone, we'll have to type all that!
But what if we make a shortcut?
We can!
We use functions. Imagine it as teaching the cat to do something new!

Let's go in-depth!

  • Firstly, of course, we need to use the keyword function. This tells the program we're teaching it something new!
  • Then, we can name the function anything, for instance here we name it rickroll!
  • We also have normal brackets (). We'll talk more about them later, but for now let's just ignore them!
  • Finally, we have the code inside curved brackets {}! This is what we'll teach.

Here's a really bad analogy!

Sam just made a robot (who he calls Sam Jr.), he wants to teach him to walk!
If Sam asks him to walk, he won't understand.
So, he teaches him to move his right foot forward, then his left foot etc!
Now, Sam Jr. understands how to walk!
When Sam asks him to walk, he moves his right foot forward, then his left foot, etc!

That's how we teach the computer!

  • At the beginning, if we ask the computer to rickroll, it won't understand!
  • Then we teach the computer how to rickroll by outputting Never gonna give you up!
  • Finally, the computer understands how to rickroll.
  • If we ask it to rickroll, it will output Never gonna give you up :)
    Besides teaching the computer, the actual purpose of functions is to shorten the code!
    Instead of typing echo "Never gonna give you up"; every time we want to rickroll, here we just need to type rickroll()!

Hopefully you understand, but if you don't feel free to read that again!

But what are those normal brackets () for??
They're for variables needed!

In our rickroll function, there was no variable needed. But what if we actually need a variable?

Let's make a function that adds the numbers given!

Last but not least, we have the return keyword.

Let's assign a variable to the sum of those 2 numbers!

The code above won't work because add(12,2) doesn't have a value!
To give it a value, we use the return keyword :)

Now, this code works because add(12,2) has the value 14!

If you didn't understand, read it again :)

But if you did...

THE EXCITING PART: WEBSITE-BASED PHP!

Note: PLEASE learn HTML first before continuing here!
You might have seen the example code at the beginning:

As I said earlier, you can submit the form but nothing will happen because the data isn't sent to the server!
Data that is sent to the server is just like a variable - it has a name and value!

So how do we send it to the server?
Well firstly, we'll need to know about some attributes in HTML!

  • In the <input> tag, there is an attribute called name! This is basically the "variable name" of the data that will be sent to the server! The value of the data is whatever the user typed in the <input> field :)

In the <form> tag, there are 2 attributes we need to know!

  • The action attribute is basically where the website should redirect to after submitting the form!
  • The method attribute is used to determine how the data should be sent! It can have 2 values: get or post! I'll explain the difference soon, but here we'll use get :)
    So now here's our code:

Let's type a random name in the input field and submit it!

When submitting we are redirected to the page get.php, but nothing happens because the page is still empty!

So, in our get.php file, we need to get the data that was sent to the servers!
Since the method attribute is get, we need to use $_GET to get the data!
Let's type:

However, when we use the post method, we must use $_POST instead of $_GET!
Here are the differences between the methods post and get!

CriteriaPostGet
SpeedSlowerFaster
VisibilityNot visible in URLVisible in URL
Information sentUnlimited dataLimited data
Usage$_POST$_GET

What does visible in URL mean?

Well, it means you can see the name and value in the URL, for instance in https://replit.com/@Th3Coder?tab=posts

See tab=posts after the question mark?
tab is the name there and posts is the value! It uses the get method!
There also used to be a comment tab, but it got removed for some reason :(
Several values are split with the ampersand (&), for example https://replit.com/@Th3Coder/PHP?embed=true&tab=code
Well okay, now get.php outputs the name we entered, but the website owner still doesn't know the information entered!

How do we send it to the owner then?

There are probably several ways to do this, but I recommend adding the text to a file!

If we want to add text to a file, of course we'll have to open that file first!
There are a few modes to open a file, but I suggest using:

  • a for adding text to the file
  • w to erase all text in the file and add text to it and create the file if it doesn't exist!

To open a file in PHP, we need to use the fopen function! It basically stands for file open :)
For instance, let's make a file named text.txt and open the file in our get.php file!

So we've opened the file, now we need to add text to it!
For that we use the function fwrite, which basically stands for file write!

Oh yeah, \n inserts a new line in the text.txt file. But for .html pages, we should use <br> instead!

...and we should close the file after opening it!

For that, we use the fclose function which obviously stands for file close :)

We can also use the file function, which creates an array by splitting the file by lines!

For instance, if the file text.txt is

Then file("text.txt") will be array("A", "B", "C", " I forgot")!

We can also use PHP in the same page as the form! For that, we don't need the action attribute for the <form> tag, also I recommend you to use the post method :)
We also need to use the isset function!
Basically, isset checks whether any data has been sent!

For reference, you can see PHP in action HERE!

Ending

Thank you SO MUCH for reading this, and it's fine if you skipped some parts :)

If you have any questions, feedbacks, suggestions, or corrections, FEEL FREE TO TELL ME!
Also, sorry if I explained anything wrong... Please tell me if I did! :)

Finally, even though this tutorial's REALLY long, search it up in the internet to learn more as there are A LOT of functions I didn't cover here!

Bye, thank you again and have a nice day!

Voters
LUISROBERTORO17
Th3Coder
Comments
hotnewtop
Th3Coder

This tutorial is REALLY long XD, should I shorten it?

Highwayman

personally, I like that you put everything in one place. It's just easier to follow. Have you ever noticed how some tutorial series have a MASSIVE following in the first post, but almost nothing in the second?
@Th3Coder

Highwayman

btw, that actually is pretty great art XP
I like it!
@Th3Coder

Th3Coder

@Highwayman I've never seen tutorials like what you described, thanks though! This took a week to type XD

Highwayman

Really?
..🤷‍♂️
It's just hard to keep up the hype sometimes I'm pretty sure.

I have a tutorial that I still haven't finished after two years XD

@Th3Coder

Th3Coder

@Highwayman woah, 2 YEARS??? What tutorial is it?

Highwayman

I think it's like my only tutorial post- here one sec.
@Th3Coder

Highwayman
Th3Coder

@Highwayman ohh, cool! Finish it

Highwayman

lol, I actually am trying to finish it at some point. XP
@Th3Coder

Th3Coder

@Highwayman good luck doing that! You can make small edits one at a time, I did that with my privacy tutorial (not avertising, by the way!) :)

Highwayman

Yeah! that's what I've been trying to do, but it's kinda hard cause I'm supposed to have like..a ..structure..? Like- plot? I mean like...uh...plan? Like I start writing in one direction a month or so ago, and then I forget where I was going and... yeah..
@Th3Coder