DEV Community

Cover image for Basic PHP course
Walter Nascimento
Walter Nascimento

Posted on

Basic PHP course

[Clique aqui para ler em português]

Which is?

PHP is a language that allows you to create dynamic WEB sites, enabling interaction with the user through forms, URL parameters and links.

PHP is a popular general-purpose scripting language that is especially suited to web development.

Fast, flexible and pragmatic, PHP powers everything from your blog to the most popular websites in the world.

Although PHP is widely used in web environments, it is quite flexible and can also be used for creating desktop applications and so on.

History

The PHP language was conceived during the fall of 1994 by Rasmus Lerdorf. There were several versions to get to the PHP that we have today, for a more complete reading visit the site https://www.php.net/manual/pt_BR/history.php.php

Installing PHP

To install PHP you just have to download the desired version file directly from the official website https://www.php.net/downloads and configure the environment variable, if you use linux it’s even simpler, just run apt install php and php will be installed on your machine (in case you need to define the version you want to install eg 5.4, 7.1, 7.3, 8.0 and etc).

Running PHP

The php can be used directly in the terminal, for that use the command php -a, with that you will be able to execute all the commands directly in the terminal (interactive terminal).

To execute a command we will simply type echo “Hello World”; and with that the text will be displayed in the terminal, if you want to exit the terminal type quit (or CTRL+C).

Embedded web server

Since version 5.4 the PHP CLI comes with a built-in http server. It can be used for development and testing or for demonstrations of applications that run in controlled environments.

If you want to use it for development, follow the example below:

cd ~/public_html
php -S localhost:8000
php -S 0.0.0.0:80 // So the application is already exposed within your network for your ip
Enter fullscreen mode Exit fullscreen mode

Creating a file

To create a php file, you need at the beginning of the file put the instruction <?php this declares that the content will be processed via php, to complete the creation of the file save with the extension .php (example index.php), to execute the file type php index.php.
Tools

To work with PHP you need two important tools the first is the browser (browser) as it will display the page you are creating (remembering that we can use the php cli itself to display information but as the objective is to work with the php for web the ideal and already getting used to the browser) and the second is an editor, although we can work with a standard file editor (notepad and etc) the better the tool the faster we create our pages.

Browsers:

Text Editor:

Basic Syntax

Comments

To use comments in php you can use it in two ways, the first /** */ is mainly used for multiline comments, and for only one line it is mainly used //

PHP supports ‘C’, ‘C++’ and Unix shell (Perl style) comments. For example:

<?php
echo 'This is a test'; // One-line comment style in C++ 
/* This is a multiline comment yet another line of comment */
echo 'This is yet another test'; 
echo 'A final test'; # This is a one-line shell-style comment
Enter fullscreen mode Exit fullscreen mode

Short echo

PHP includes a short tag echo <?= which is shorthand for <?php echo.

Example:

<?php echo $var; ?> // this
<?= $var; ?> // turns into that
Enter fullscreen mode Exit fullscreen mode

Variables

Whenever you have information that needs to be saved or some value that will be manipulated, We use variables, and to use variables in PHP, we always add the $ symbol at the beginning of the word, and to assign the value to a variable we add the equal(=) operator ) and the value to be assigned, for example:

$age = 25;
Enter fullscreen mode Exit fullscreen mode

Data type

PHP has several data types, there are scalar types

Escalares Compostos Especiais
bool array resource
int object NULL
float callable
string iterable

Example

$age = 21;
$wage = 1000.301;
$division = 10 / 3;
$text = "Olá mundo";
$boolean = true;
echo getType($boolean);
Enter fullscreen mode Exit fullscreen mode

Note: Despite having several data types, as php is weakly typed, so being a beginner you don’t need to worry too much about the initial data type, because even if the variable is string, you can still make a mathematical expression with her.

Strings

When setting a value in quotes, php already transforms it into a string.

If you want to set a single value use single quotes, if you want to read the value of a variable use double quotes

Ex.:

$test = 'ok';
$output = '$test';
echo($output); // Prints the text $test
$output = "$test";
echo($output); // Prints the text ok
Enter fullscreen mode Exit fullscreen mode

To concatenate strings we use the period (.) and inside the double quotes we can use variables.

Operations

To do operations in PHP is very simple, simply using the operators of addition, subtraction and so on.

$sum = 2 + 2;
$minus = 22;
$multiplication = 2 * 2;
$division = 2/2;
$potency = 2 ** 2;
$rest = 2 % 2;
Enter fullscreen mode Exit fullscreen mode

Control Structures

Decisions in code (IF)

To make decisions we use the IF conditions, the if makes a check if something is true and if it is it executes a {} statement block, example

$age = 21;
if($age > 18) {
      echo "over 18";
}
Enter fullscreen mode Exit fullscreen mode

Decisions in code (ELSE)

Else is the opposite case of if, so every if statement can be followed by an else, example:

$age = 21;
if($age > 18) {
    echo "over 18";
} else {
    echo "under 18";
}
Enter fullscreen mode Exit fullscreen mode

Code decisions (ELSE IF and ELSEIF)

The Else if is when you fall to the else but there is no statement something like that

if(false) {

} else
Enter fullscreen mode Exit fullscreen mode

So the first statement after the else is executed, in this case the if, and the elseif is a reserved word to do a check after the if fails and falls into the elseif, in short, they both do the same thing in different ways.

if(false) {

} elseif(true){

}
Enter fullscreen mode Exit fullscreen mode

NOTE: all expressions that were written and evaluated by if must be able to be represented as a boolean value.

If you use some other value (string, int, float, etc), PHP itself will convert these values to Boolean following the rules explained in the documentation.

Ternary Operator

When the if and/or else has only one statement, then it is not mandatory to use braces {}, but by default it is more used with braces regardless of having only one line or not. Also, when there is only one line to be executed, we have another option for making decisions. If we need, for example, to assign the value to a variable based on some condition, we can use what is called a ternary operator. Its syntax is as follows:

$variable = $condition ? $ValueIfTrue : $ValueIfFalse;
Enter fullscreen mode Exit fullscreen mode

Repetitions (loop)

while

While loops are the simplest loop types in PHP. It behaves similarly to C. The basic format of a while statement is:

while (expr)
    statement
Enter fullscreen mode Exit fullscreen mode

The purpose of the while statement is simple. It will tell PHP to execute nested statements repeatedly as long as the while expression evaluates to true.

do-while

Do-while loops are very similar to while loops, except that the evaluation expression is checked at the end of each iteration rather than at the beginning. The biggest difference for the while loop is that the first iteration of the do-while loop is always executed (the evaluation expression is only executed at the end of the iteration), whereas in the while loop it is not necessarily executed (the evaluation expression is executed at the beginning of each iteration, if it evaluates to false at the beginning, the execution of the loop will be aborted immediately).

There is only one syntax for the do-while loop.

$i = 0;do {
    echo $i;
} while ($i > 0);
Enter fullscreen mode Exit fullscreen mode

for

For loops are the most complex in PHP. It has similar behavior to C. The syntax of the for loop is:

for (expr1; expr2; expr3)
    statement
Enter fullscreen mode Exit fullscreen mode

The first expression (expr1) is evaluated (executed) once, unconditionally, at the beginning of the loop.

At the beginning of each iteration expr2 is evaluated. If it evaluates to true, the loop will continue and the nested statements will be executed. If it evaluates to false, loop execution will terminate.

At the end of each iteration, expr3 is evaluated (executed).

/* example 1 */
for ($i = 1; $i <= 10; $i++) {
    echo $i;
}

/* example 2 */
for ($i = 1; ; $i++) {
    if ($i > 10) {
        break;
    }
    echo $i;
}

/* example 3 */
$i = 1;
for (; ; ) {
    if ($i > 10) {
        break;
    }
    echo $i;
    $i++;
}

/* example 4 */
for ($i = 1, $j = 0; $i <= 10; $j += $i, print $i, $i++);
Enter fullscreen mode Exit fullscreen mode

foreach

The foreach constructor provides an easy way to iterate over arrays. foreach only works on arrays and objects, and will throw an error when trying to use it on a variable with a different data type or on an uninitialized variable. It has two syntaxes:

foreach (array_expression as $value)
    statement

foreach (array_expression as $key => $value)
    statement
Enter fullscreen mode Exit fullscreen mode

Arrays

An array in PHP is actually an ordered map. A map is a type that relates values to keys. This type is optimized for several different uses: it can be treated as an array, a list (vector), HashTables (which is an implementation of maps), dictionary, collection, stack, queue and probably more. They are dynamic in size, can have strings as their indices, and can be manipulated in different ways.

array(
    chave => valor,
    chave2 => valor2,
    chave3 => valor3,
    
);
Enter fullscreen mode Exit fullscreen mode

Php only works with keys being numeric or string, boolean, float and etc will be forced to be converted.

$array = array(
    1 => "a",
    "1" => "b",
    1.5 => "c",
    true => "d",
);
var_dump($array);
Enter fullscreen mode Exit fullscreen mode

Function

Subroutine executes what it has to execute and doesn’t return anything, a function returns something.

A function can be defined using the following syntax:

function foo ($arg_1, $arg_2, /* …, */ $arg_n)
{
    echo "Function example.\n";
    return $returned_value;
}
Enter fullscreen mode Exit fullscreen mode

Any valid PHP code can appear inside a function, even other functions and class definitions.

Anonymous functions

Anonymous functions, also known as closures, allow you to create functions that don’t have the specified name. They are most useful as the value of callback parameters, but they can have many other uses.

Anonymous functions are implemented using the Closure class

echo preg_replace_callback(~-([a-z])~, function ($match) {
    return strtoupper($match[1]);
}, hello-world);
// outputs helloWorld
Enter fullscreen mode Exit fullscreen mode

Recursive functions

A recursive function is nothing less than a function that invokes itself.

For that, there must necessarily be a condition in which the functions stop calling each other, and when they reach a certain argument value, they stop calling.

function fat($number){
    if($number==0) {
        return 1;
    }
    return $number * fat($number-1);
}
Enter fullscreen mode Exit fullscreen mode

Coding Standard

Every language leaves a range of possibilities to work with it, HTML is no different, you can write tags in uppercase or lowercase or not put certain attributes and so on.

To make writing more compatible, the ideal is to have a coding standard.

Documentation

Every language has documentation and PHP would be no different, a tool I really like to read documentation is DevDocs.

if you need any tips faster, use devhints

For usage tips, visit phptherightway


Thanks for reading!

If you have any questions, complaints or tips, you can leave them here in the comments. I will be happy to answer!

😊😊 See you! 😊😊

Top comments (0)