DEV Community

Cover image for PHP Tutorial: Get started with PHP from scratch
Hunter Johnson for Educative

Posted on • Originally published at educative.io

PHP Tutorial: Get started with PHP from scratch

PHP is the ideal language for new developers. It is simple, fast, and intuitive. It is also very similar to other programming languages, like C, so you can pick other languages up faster with PHP knowledge.

Today we’ll get you started with PHP from the very beginning, breaking down what PHP is, why you should learn it, and some of its unique advantages. Then we’ll walk you through your first PHP “Hello World” program. Finally, we’ll cover the core PHP syntax and work through exercises.

By the end, you’ll have a solid foundation of basic PHP concepts and will be able to advance to intermediate topics. No prior knowledge of PHP is required, but to be successful in this tutorial, some general knowledge of programming will help you get the most from our exercises.

For a quick introduction, check out The Absolute Beginner’s Guide to Programming.

Here’s what we’ll cover today:

What is PHP?

PHP is a recursive acronym for PHP: Hypertext Preprocessor. It is a popular, open-source scripting language that is similar to C and especially suited for web development. PHP can be directly embedded into HTML using the <? php and ?> instructions. These simple code instructions allow you to jump between HTML and PHP code without the need for extra commands used with C or Perl.

Another unique factor of PHP is that its code is executed on the server rather than client-side, or the side of the internet that a user sees. Once executed, PHP code generates HTML, which is then sent client-side. This makes PHP very secure and ensures that users cannot see what’s going on behind the screen.

Why should you learn PHP?

PHP is a great starting point for any new developer. PHP’s simplicity means it’s easier to pick up than other languages. Even if you don’t want to work in web development, the syntax and object-oriented thinking skills of PHP can give you a significant advantage when learning other OOP languages like Java or C++.

PHP also comes with a massive community. In fact, Github reports that PHP is the 5th most popular language in the world, PHP has the 3rd largest community on StackOverflow. This large community ensures you’ll never be without help if you get stuck.

Finally, PHP is a widely sought skill in the modern digital economy, and demand is growing. Popular sites like Facebook, Wikipedia, Yahoo, and Flickr are all built on PHP. In fact, data collected by Codementor found that PHP is used for 80% of the world's top 10 million websites and about 40% of all sites on the internet!

PHP has also gained popularity as the go-to for small businesses. This is because intuitive content management systems like Wordpress and Wix are written in PHP. A lot of PHP web developers are freelance workers who help launch new websites for businesses. The need for PHP developers is increasing.

What is PHP used for?

PHP is most often used in server-side web development. Thanks to server-side execution, PHP is great for dynamic web pages, a type of site which updates periodically or reacts to certain events. PHP’s secure function-hiding abilities also make it ideal for working with sensitive financial or personal information.

Online stores are a place we can see both of these strengths come into play. For example, PHP is used in the “shopping cart” functions of many sites. This is because PHP only sends the outcome of adding the item or completed transaction without giving access to the function.

Beyond this, PHP is also used in command-side scripting and graphical user interface design (GUI). PHP shows its value as a widely available and generalized language capable of running on nearly any operating system or database.

Advantages of PHP

  • Quick and Easy to Learn: PHP is beginner friendly and can be learned quickly relative to other languages. It’s also often considered a great first language.

  • Large Community: PHP has a large user base and online support community.

  • Widely Applicable: PHP can be used on any operating system or database.

  • Open Source: PHP is free to adopt and download along with all of its tools. This also means that the language is highly receptive to community feedback.

  • Great Performance:
    PHP uses its own memory space rather than an overhead server.

Get started with PHP: Hello World

Now that we know a bit more about PHP, let's get into writing our first Hello World program. Hello World is a simple program that developers write as their first program with a new language. You can either follow along on your own PHP editor (see below), or you can use Educative’s built in code environment.

To do this on your own, you’ll need:

  • Text Editor (Notepad, Sublime etc.)
  • XAMPP for setting up our personal web server

If you’d prefer not to download anything right now and would rather follow along with Educative’s coding environment, skip to the “Hello World in PHP” section below.

Setting up your XAMPP server

Once you’ve downloaded XAMPP, we’ll need to set up a server. To do that, go to the directory where you installed XAMPP, usually found at C:\xampp. Then go to the folder called htdocs and create a folder inside it called MySite. This file path will act as your Local URL for the rest of the project. You’ll save all site related files here like .html, .php, etc.

Now that we have our folder set up, open your text editor and save a file to that folder called index.php. You’ll write the Hello World example outlined below in this file.

Hello World in PHP

For your first line, type the line:

<?php>
Enter fullscreen mode Exit fullscreen mode

This is the PHP opener tag. This tag can be placed anywhere in a document to signify that the code that comes after is PHP.

For your second line, write:

echo Hello, world!;
Enter fullscreen mode Exit fullscreen mode

This calls the built in echo function. This function tells the program to print anything that follows within the quotations, in this case Hello, world!. The echo command can also take variables to print, which we’ll learn more about later.

Lines that express an action being carried out, like calling the echo function with a parameter, are called statements. Each statement in PHP must be concluded with a semicolon to mark where the statement ends.

Finally, write the line:

?>
Enter fullscreen mode Exit fullscreen mode

This is PHP’s closing tag that marks the end of the document’s PHP code section. Any code past this tag will not be treated as PHP and may result in errors.

Here’s what our document will look like by the end, it will print "Hello, World!":

<?php 
echo "Hello, World!";
?> 
Enter fullscreen mode Exit fullscreen mode

If you’re following along, save this file and check it’s within our MySite folder with the name index. php. We’ll now use XAMPP to view this code in a web browser.

Open your XAMPP Control Panel either via the desktop icon or on the xampp-control application in the directory folder. Then, run Apache and mySQL by clicking the “Start” button on their respective rows. Apache will act as our web server to host a local site while mySQL will act as our database to store site information.

Now, open your web browser and type localhost into the address bar. This will bring up a language select menu, simply select your desired language and you’ll be redirected. If an XAMPP menu comes up, your local server is running correctly.

To see our PHP Hello World site, type localhost/MySite. You should see a mostly white page with the words “Hello, World!” written in the top left corner.

PHP automatically reads files named index by default when a folder is selected. To open files of a different name, you’ll need to add a forward slash followed by the file name in the address bar.
For example: localhost/MySite/hello.php

Congratulations, you’ve just completed your first PHP website! Now that we’ve run through the process once, let's look at some more standard syntax we can use in the future.

Standard PHP Syntax

In programming, syntax refers to the rules and standards we use for writing a language. This is just like any spoken. or written language. Syntax determines how meaning is made our of predetermined words, structures, or norms. Let's look at the standard syntax. of PHP.

HTML Embedded

While our file features just PHP code, files with the .php extension can also include HTML code. PHP code must be started and ended with the tags <?php> and ?>. Anything outside of these tags is considered HTML code.

Here’s an example of PHP code being embedded along with HTML code in a .php file:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Embedded PHP</title>
</head>
<body>
    <h1>
         <?php 
         echo "Hello, world!\n"; 
         ?>
    </h1>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

For a beginner’s tutorial to HTML, see our previous article, HTML Beginner's Tutorial: build a webpage from scratch with HTML

Comments in PHP

Comments are a feature in any programming language which allows you to write labels for your code that will be ignored at execution. This is helpful when working on project with other developers as your labels can help them understand what you’re trying to do in code without having to figure it out from scratch.

To create a single line comment in PHP, you can begin the line with either // or #. For a multiple line comment, begin the comment with /* and end it with */.

<?php
//prints a Hello World statement

/* This is PHP code
that prints Hello World
*/
echo "Hello, World!";
?> 
Enter fullscreen mode Exit fullscreen mode

Case Sensitive Variables

Our final general syntax rule is that variable names are case sensitive in PHP. This means that if you name a variable var then neither Var nor VAR will be able to call that variable.
Function and class names on the other hand are not case-sensitive. This means that func1, Func1, FUNC1 are the same.

Key PHP terms and concepts

Now that we’ve covered some general syntax rules and made our first PHP site, let’s learn some of the key terms and concepts you’ll use regularly in PHP programs. Try working on the exercises within to get hands on learning!

Variables

A variable in any programming language is a prenamed piece of code with a particular meaning. Variables are one of the essential parts of any computer program. You can declare a variable in PHP using a $ sign, followed by its name, such as $myVariable.

Unlike other languages, PHP doesn’t require the user to set the variable’s data type. Instead, the data type is automatically detected by the value assigned to the variable. For example:

<?php
$str = "I will be back by "; //This is detected as a string.
$num = 5; //This is detected as an integer

echo $str; 
echo $num;
?>
Enter fullscreen mode Exit fullscreen mode

Output: I will be back by 5

Arrays

An array is like a list of values. The simplest form of an array is indexed by an integer, and ordered by the index, with the first element lying at index 0.

Declaring foo array in PHP:

<?php
$foo = array(1, 2, 3); // An array of integers created using array function
echo $foo[0]; 
?>
Enter fullscreen mode Exit fullscreen mode

Output: 1

Arrays can also associate a key other than an integer index to a value. In PHP, all arrays are associative arrays behind the scenes, but when we refer to an associative array explicitly, we usually mean one that contains one or more keys that aren’t integers, such as strings.

Associating key as index in array:

<?php
$array = array();
$array["foo"] = "bar";
$array["bar"] = "quux";
$array[42] = "hello";


echo $array["foo"]; 
?>
Enter fullscreen mode Exit fullscreen mode

Output: bar

Here, the index associated with the bar value is not the integer 0 but is the string foo. While integer indices are the most common type of array, the flexibility to have different index types is very handy in certain situations.

Strings

A string is a variable data type consisting of an array of characters. These characters are indexed by their position in the collection. Like arrays, indexes begin at zero and count upwards as you progress through the string. These are used to store and manipulate words and phrases in PHP.

For example, our previous Hello World code prints the string Hello, World!. H is the character value at index 0, E is the value at index 1, and so on.

Operators

An operator is an element that takes one or more values, (called expressions in programming jargon), and yields another value. This makes the construction itself become an expression. For instance, when you add two numbers, say 2 and 5 (values) it yields 7 (value), such that the construction itself becomes an expression, i.e. 2+5=7.

Some of the most common operators are part of two types: arithmetic operators and comparison operators

Arithmetic operators:

Arithmetic operators are used to perform basic arithmetic. Below is a guide to each arithmetic operator in PHP:

PHP

The modulus operator returns the remainder when $a is divided by $b. 5 % 4 = 1

To see each operator in action, run the code below!

<?php
$a = 18;
$b = 4;
echo "$a + $b = " . ($a + $b); //addition
echo "\n";
echo "$a - $b = " . ($a - $b); //subtraction
echo "\n";
echo "($a * $b) = " . ($a * $b); //multiplication
echo "\n";
echo "$a / $b = " . ($a / $b); //division
echo "\n";
echo "$a % $b = " . ($a % $b); //modulus
echo "\n";
?>
Enter fullscreen mode Exit fullscreen mode

Output:
18 + 4 = 22
18 - 4 = 14
(18 * 4) = 72
18 / 4 = 4.5
18 % 4 = 2

Comparison operators allow you to compare to values. Each operator returns either true or false. The operator returns true if the comparison is accurate and false if it is not.

Below is a guide to the basic comparison operators in PHP:

PHP operators

Conditional Statements

Code often needs to act differently depending on the conditions of the program. Conditional statements determine which conditions the program will check.

Conditional statements often come up in real life situations as the factors that affect our behavior. For example, consider the sentence “if I am too warm, I will turn on a fan”. Here, the condition factor that affects my behavior would be: if(Ryan = too warm).

Within the PHP programming language, an if-else statement is the simplest way of creating a branch within your program.

This statement is broken down into 4 parts:

  • if() is a keyword that signals the beginning of a conditional statement
  • The condition is a certain state within the if parentheses that is checked at execution
  • If the condition is met, statements enclosed within the if curly brackets are executed
  • If the condition is not met, the statements enclosed within the else curly brackets are executed

Let’s see an example of this statement:

<?php
$a = 50; //change the value of "a" so it is less than b in order to execute the else statement
$b = 15;
if ($a > $b)
{
    //this code is executed only if $a is greater than $b
    echo "a is greater than b";

}
else
{
    //this code is executed if the preceding "if" condition evaluated to false
    echo "a is less than b";
}
?>
Enter fullscreen mode Exit fullscreen mode

Output:
a is greater than b

You can also nest conditionals so that the else section contains an if check of its own. This can be done as many times as you need so long as it has a plain else as the conclusion. Below is an example:

<?php
if (condition)
else if
else if
else
?>
Enter fullscreen mode Exit fullscreen mode

Conditional Statement Exercise:

Prompt: Write a program which will check whether a given integer $number is even or odd. You’re given a variable $temp, set this to 0 if the $number is even and 1 if the $number is odd.

Try to solve this on your own first. If you need help, don't worry. Solution will be given below.

<?php
// your code here
?>
Enter fullscreen mode Exit fullscreen mode

Here is the solution of conditional statement exercise:

<?php
$number= 23;
$temp=-1; //set temp to 0 if number is even
//set temp to 1 if number is odd

echo  "Computing whether $number is an even or odd integer\n";

if($number % 2 == 0){
  echo "$number is an even integer\n";
  $temp = 0;

}else{
  echo "$number is an odd integer ";
  $temp = 1;
}
?>
Enter fullscreen mode Exit fullscreen mode

Loops

Loops allow a programmer to execute the same block of code repeatedly instead of rewriting code that needs to be executed multiple times. The type of loop and what condition statements have been supplied decide how many times a loop will repeat.

The most common type of loop in PHP is the while loop. The while loop consists of a condition statement and a set of statements. While that condition is true, the loop will continue executing the set of statements.

Here’s an example of a while loop in PHP:

<?php
$x = 4;
$y = 0;
while ($y <= 10)
{ // the while loop will run till y<=10 condition is being met
    $y += $x;
    $x += 1;
} //the loop will iterate 3 times
echo "The value of x is: $x\n";
echo "The value of y is: $y\n";
?>
Enter fullscreen mode Exit fullscreen mode

Output:
The value of x is: 7
The value of y is: 15

Notice that the statement set within the while loop changes the value of the $y variable used in the condition statement. This ensures that the loop will terminate at some point, as each repetition progresses the variable closer to becoming false. Ensure that the measured condition is affected by each loop to avoid infinite loops.

Loops Exercise:

Prompt: Create a while loop that multiplies variable input by itself until it is greater than or equal to 100 and records the number of loops.

Sample Input: 10

Sample Output: 2

<?php
// your code here
?>
Enter fullscreen mode Exit fullscreen mode

Here is the solution of loops:

<?php
$loops = 0;
$input = 2;

while($input < 100)
{
$input = $input * $input;
$loops = $loops + 1;
}
echo $loops;
?>
Enter fullscreen mode Exit fullscreen mode

Functions

A function is a block of code that performs a specific task.

Let’s discuss a real-life example to understand the concept better. Suppose that a headmaster wants a teacher to calculate the average marks of the students in a class for a particular subject. The teacher will collect all the grades of the students for that subject, calculate the average grade, and report the result to the headmaster.

Functions work in a similar way. They take the required information to perform a task as input parameter(s), perform the required operations on these parameters, and then return the final answer.

In PHP, there are two types of functions:

  • Built-in functions
  • User-defined functions

Built-in functions are functions that are pre-defined for all PHP users and can just be called without the user having to create them. The echo function we used earlier in the article is on example of a built-in function.

User-defined functions allow you to create custom functions. User functions are created like so:

<?php
function myFunction ($a) {
//code;
}
?>
Enter fullscreen mode Exit fullscreen mode

First , function is the keyword which specifies that we’re creating a function. Then myFunction is the identifying name for the function that we will call to execute the function. The variable a is a parameter that is given to the function to use for its operations.

Functions can call for as many or as few parameters as you want. Finally, within the curly brackets is where we’d find the code for what this function does. To call a function, you write the function's name with any parameters required and end with a semicolon.

myFunction(a);
Enter fullscreen mode Exit fullscreen mode

Lets see a full example:

<?php
function myFunction() //function that outputs some text
{
    echo "This is a user-defined function";
}
// Calling the function
myFunction();
?>
Enter fullscreen mode Exit fullscreen mode

Output: This is a user-defined function

Functions Exercise:

Prompt: Create a function sum that takes two integer parameters and returns their sum.

Sample Input: 4, 5

Sample Output: 9

<?php
// your code here

//Calling and printing value of the "sum()" function
echo sum(4,5);
?>
Enter fullscreen mode Exit fullscreen mode

Here is the solution:

<?php
  function sum($num1, $num2){
    return $num1+$num2;
  }
?>
Enter fullscreen mode Exit fullscreen mode

Classes

Like C++ and Java, PHP also supports object-oriented programming. This means that classes and objects can be created in PHP.

Classes are the blueprints of objects. One of the big differences between functions and classes is that a class contains both data (variables) and functions to form a package. A class is a user-defined data type, which includes local methods and local variables.

  • Methods are functions contained within a class.
  • Properties are variables contained within a class.

An object is an individual instance of the data structure defined by a class. We define a class once and then make many objects that belong to that class.

Here is an example of how a class is defined:

<?php
class Shape{
  public $sides = 0; // first property
  public $name= " "; // second property 

  public function description(){ //first method
    echo "A $this->name with $this->sides sides.";
  }
}
?>
Enter fullscreen mode Exit fullscreen mode

Here, we can see the properties sides and name as well as the method description. The public tag before each property and method allows them to be accessed by nearly anything within the program. We can then make objects of the shape type that represent different shapes. Each shape has a specific number of sides and a specific name, so we have to set each for the new object. Our description method uses these properties to print a correct description.

Here’s an example of how we’d create an object using the shape class:

<?php
$myShape1 = new Shape; //creating an object called myShape1
$myShape1->sides = 3; //setting the "sides" property to 3
$myShape1->name = "triangle"; //setting the "name" property to triangle
$myShape1->description(); //"A triangle with 3 sides"
?>
Enter fullscreen mode Exit fullscreen mode

Classes and Objects are used to make your code more efficient and less repetitive by grouping similar tasks. A class is used to define the actions and data structure used to build objects. The objects are then built using this predefined structure.

Classes Exercise

Prompt: Write a class called Triangle having two public variables for length and height and one member function called area which will return the area of the right angle triangle. You can calculate the area of a triangle using Area = 1/2(length)(height).

Sample input: 4, 5

Sample Output: 10

<?php

//define your class here
// name your class Triangle
//name your function area



//This is a test function. Do not change it.  
function test($length, $height) {

  $answer=0;
  $obj = new Triangle;
  $obj->length= $length;
  $obj->height= $height;
  $answer = $obj->area();

  return $answer;
}
Enter fullscreen mode Exit fullscreen mode

Here is the solution:

<?php
class Triangle {

   public $length=0;
   public $height=0;
   public function area()
   {

       return ($this->length*$this->height)/2;
    }
};



//This is a test function. Do not change it.  
function test($length, $height) {

  $answer=0;
  $obj = new Triangle;
  $obj->length= $length;
  $obj->height= $height;
  $answer = $obj->area();
  return $answer;
}

//calling test function
 echo test(8,9);

?>
Enter fullscreen mode Exit fullscreen mode

What to learn next

Congratulations! You’ve just completed your first introduction to PHP. You just learned some background on PHP, wrote your first program, and worked through some of the key PHP concepts. You’re ready to learn more advanced PHP concepts like inheritance and multidirectional arrays.

As a beginner, I recommend building the following projects to continue learning:

  • Create a to-do list with PHP and mySQL
  • Build an online shopping cart
  • Build a basic forum with login registration
  • Design a simple image gallery

To get you started learning these advanced topic Educative has created a free Learn PHP from Scratch course. Diver deeper into each of the topics covered here with interactive examples. By the end, you’ll be well on your way to becoming a professional web developer!

Continue learning about web dev and PHP on Educative

Start a discussion

Why do you think PHP is a good language to learn first? Was this article helpful? Let us know in the comments below!

Top comments (3)

Collapse
 
gpisano97 profile image
gpisano97

I'm a PHP developer, but i think that the best way to start developing is learn C and C++. With an high level aknowledgement of C and C++ you can migrate to every languages, all the principles are the same and usually have to deal with types, abstract, and complex data structures is a real advantages.

Collapse
 
dequilla3 profile image
Kim Dequilla

C, C++, C# and Java

Collapse
 
gpisano97 profile image
gpisano97

Yes, during my formations i mastered all this languages!