PHP Basics for Beginners

PHP ~ 8 minutes

# Welcome to PHP

Hello and welcome! In this tutorial, we will learn the basics of PHP. PHP is a popular language for building websites. Big projects like WordPress and Laravel use it. You can read about it on the official site, php.net.

PHP runs on the server, not in the browser. The server runs your PHP code, and then it sends the result to the visitor as plain HTML. The visitor never sees your PHP code. Do not worry if this sounds new. We will practise with small examples.

What you will learn

  • How to run a PHP file
  • How to use variables, strings and arrays
  • How to make decisions and repeat tasks
  • How to write your own function
Check your PHP version
Code Copied to Clipboard

# Your first PHP file

If the command above shows a version number, PHP is ready. If not, please install PHP first. You can find help in the PHP installation guide.

Now, please create a file named hello.php. Every PHP file starts with the opening tag <?php. After that, we write our statements. Each statement ends with a semicolon. The word echo prints text. Look at the next block and type it into your file.

hello.php
Code Copied to Clipboard

# Run the script

Now let us run the file. PHP has a command line tool, so you do not need a web server yet. Open your terminal in the same folder as hello.php. Then type the command in the next block. You should see your two messages printed on the screen. Well done, this is your first PHP program!

Run hello.php
Code Copied to Clipboard

Watch the semicolons

The most common beginner error is a missing semicolon. PHP will show a message like Parse error: syntax error. It also tells you the line number. Please read the message slowly. The real mistake is often on the line just before the one shown. Fix it, save the file, and run it again. Every programmer sees this error many times, so do not feel bad.

# Variables

A variable is a named box that holds a value. In PHP, every variable name starts with a dollar sign $. For example, $name and $age are variables. We use the equals sign to put a value inside.

PHP has several basic types. A string is text, like 'Sara'. An integer is a whole number, like 25. A float has a decimal point, like 9.99. A boolean is true or false. PHP finds the type by itself, so you do not need to declare it. The next block shows all four.

Variables and types
Code Copied to Clipboard

# Strings and arrays

Notice the dot . in the last example. In PHP, the dot joins two strings together. Also, double quotes allow you to put a variable directly inside the text, like "I am $age years old.". Single quotes do not do this.

An array holds many values in one variable. It is like a shopping list. You can make one with square brackets. Each item has a position, called an index, and counting starts from zero. You can also use names as keys. This is called an associative array. Look at the next block.

Arrays
Code Copied to Clipboard
Arrays start at zero

In PHP, the first item of an array has index 0, not 1. So $fruits[0] is apple, and $fruits[1] is banana. If you ask for an index that does not exist, PHP gives a warning about an undefined array key.

Helpful array tools

  • count($array) gives the number of items
  • $array[] = 'value' adds a new item at the end
  • in_array('value', $array) checks if a value exists

Please remember these three. You will use them almost every day.

# Making decisions

Programs must often choose between two paths. We use if, elseif and else for this. PHP checks the condition inside the brackets. If it is true, the code inside the curly braces runs.

We compare values with special signs. The sign == checks if two values are equal. The sign === is stricter, because it checks the type too. Please prefer === in your own code. It prevents many strange bugs. The next block gives a small grade example.

if and else
Code Copied to Clipboard

# Repeating tasks with loops

A loop repeats code, so you do not write the same lines again and again. The for loop is good when you know how many times to repeat. The foreach loop is perfect for arrays. It takes each item one by one.

In the next block, the first loop counts from one to three. The second loop prints every fruit in our list. Please try changing the numbers and the list, and see what happens.

for and foreach loops
Code Copied to Clipboard

Avoid endless loops

If a loop never ends, your program will hang. This happens when the condition always stays true. In a for loop, make sure the counter really changes, for example with $i++. If your terminal gets stuck, press Ctrl and C together to stop the script.

# Functions

A function is a named block of code that you can use again and again. It can take inputs, called parameters, and give back a result with the word return.

Functions keep your code clean. Instead of copying the same lines in five places, you write them once. Later, if you need to fix something, you fix it in one place only. The next block makes a function that adds tax to a price. We also give the tax rate a default value, so the caller may skip it.

Your own function
Code Copied to Clipboard

# Use the built-in server

PHP also has a small web server inside it. With it, you can see your pages in a browser, with no extra software. Please make a file named index.php in a new folder. Put some HTML and a little PHP in it, like <h1><?php echo 'Hello Web'; ?></h1>.

Then run the command in the next block from that folder. Open http://localhost:8000 in your browser to see the page. Press Ctrl and C in the terminal to stop the server when you finish.

Start the PHP server
Code Copied to Clipboard

# Good habits

Before we finish, let us talk about good habits. They will save you much time later. Use clear names for your variables, such as $totalPrice, not $x. Write small functions that do one job. Add a short comment when something is not obvious. Most of all, read the error messages. PHP tries to help you, and its messages often point straight to the problem.

Never trust user input

When you build real websites, users will type data into forms. Never trust this data. A bad user may type harmful text on purpose. Always validate the data to check that it looks right. Always escape it with htmlspecialchars() before you print it on a page. These two habits protect your site from common attacks. You can learn more in the PHP security guide.

# Summary and next steps

Congratulations! You finished the PHP basics. Let us review.

What we learned

  • PHP code runs on the server and starts with <?php
  • Variables start with $
  • Arrays hold many values, and counting starts from zero
  • if, for and foreach control the flow
  • Functions let us reuse code

Next steps

  • Build a small program, like a simple calculator
  • Learn about forms and the $_POST variable
  • Start learning a framework such as Laravel
  • Keep the PHP manual as your friend

Please practise a little every day. You are doing very well!