Jump to content

[Tutorial]Introduction to PHP/Getting Started with PHP/Operators and Functions


Recommended Posts

Posted

PHP Development and Database Interaction

 

Introduction

 

Hey there, I'm Nicolás™. In this series of tutorials/lesson, I hope you help you guys out by providing a detailed introduction into the PHP programming language and its syntax. During the later lessons, I also hope to get into database interaction with PHP (more specifically, MySQL). 

 

If you know the fundamentals of any programming language, that would be a great help, but if not, we will be going over it a lot. Stick around!

 

FAQ and Prerequisites

 

Should I learn PHP?

- Yes, of course you should! PHP has gotten a lot of bad press due to a few inconsistencies in the language, however, there's a reason why it's the most popular web programming language in the world.

 

What can I do with PHP?

- PHP is predominantly a web programming language, so you can design and create web systems. However, PHP isn't only limited to that. It's a greatly versatile language capable of a lot, so don't feel as if you'd be tied down by learning it.

 

How do I run PHP code?

- PHP is a server-side language, meaning the code isn't run client-side (on the user browsing the site, for example), unlike JavaScript, which is processed in the browser. I'll talk more about this next.

 

What do I need?

 

Okay, so all of the code we'll be using in the series will be able to be run locally, on your machine. Firstly, make sure you have a code editor ready. I personally would recommend SublimeText 2 - it's quick, easy and looks great. Available on Windows, OSX and Linux!

 

Next thing we need is a local development environment. If you're running windows, I'd recommend getting XAMPP, however for Mac, I'd use MAMP.

 

Great! Once you've got a local server running, you'll want to run Apache (the webserver). Any code should be placed in the 'htdocs' directory. Once you have a server running, you can access everything in your htdocs directory by visiting "localhost" in your browser. Provided you're running Apache on port 80. Otherwise, just add the port (i.e. http://localhost:PORT/).

 

 



 

 

PART 1 - Getting Started

 

What is PHP?

 

PHP stands for "PHP hypertext pre-processor". I'm not going to go to in-depth about how it work or its history, you can read about that yourself.

 

PHP is an interpreted language which means every time a PHP script is "run", is it re-interpreted. This is as opposed to being a compiled language. The difference being that a script coded in an interpreted language is "processed" by an interpreter on each run which completes the set of instructions given, whereas with a compiled language, source code is compiled into a form that can be directly run in the computer operating system.

 

That's a very simple way of explaining the difference. Not too difficult to understand. HTML can also be integrated into PHP. This will be further explained in the lesson.

 

Starting to code

 

I don't want to really go into too many details about the language itself, so, let's get straight into the coding!

 

There are a ton of ways to start PHP. However we are going to use the most conventional way:

 


<?php

?>

 

ALL PHP code should be inside those two tags. This is great because anything outside the tags will be processed as HTML. You can have multiple PHP tags on a page. Any code between the PHP tags will be interpreted by the interpreter, as long as the page ends in the extension .php. (This can be changed, however for simplicity's sake, let's leave like this)

 

Comments

In any programming language, comments are HUGELY important. Commenting your code is highly recommended as it can help others and yourself down the line to know what any given piece of code does. Comments can be anything you want them to be. Comments will NOT be interpreted, so they can include PHP code.

 

In PHP there are three ways to comment your code:

 


// This is a comment. This method is the most popular as it's what's used in JavaScript, too. The comment can only be ONE line.

# This is my preferred method of commenting as it's shorter. The comment can only be ONE line.

/*
This is used for block commenting
and you can have a multi-line comment
*/

 

All code I provide throughout these lessons will be commented. Get into a good commenting habit; it'll be very useful to you down the line and shows a good coding standard.

 

Semi-colons

In PHP, ALL statements should end with a semi-colon. One of the biggest mistakes people make with PHP is forgetting a semi-colon. You'll see examples of this further in.

 

Datatypes, Strings and Variables

 

If you've coded in any other programming language, you'll know all about this. We're going to look at FOUR main data types for now. I won't go into too much detail right now, just what you need to know as a beginner:

 

  • Integers - Any whole number
  • Float - Any number
  • Strings - A string of text
  • Booleans - Either TRUE or FALSE. (1 or 0 respectively)

 

We'll come back to that in a second, after looking at variables in PHP. If you're unfamiliar with what a variable is, it's basically a "storage location" stated by an identifier (the variable name) and the variable itself contains data. To access the data inside, you access the variable.

 

Variables are different to constants in that, as the name suggests, they are variable. The data a variable holds can always be changed. Variables in PHP are awesome- you don't have to set a data type as they're automatically done for you, unlike other languages.

 

To make a new variable, we use the dollar sign ($). This is followed by the name of the variable. A variable must be alpha-numeric and the only special character allowed is an underscore. Variables cannot start with numbers. There are a few reserved variables that you cannot use.

 

So, let's declare a variable:


$myVariable;

 

Great! So, like I said before, variables hold data. They can hold any time of data, however in this lesson, we'll be looking at the four I mentioned previously. To assign data to a variable, we use the assignment operator, an equals sign (=). Makes sense, right? Let's make our variable equal to the number 5:

 


$myVariable = 5;

 

Now, the variable '$variable' is an INTEGER of 5. Easy peasy! The same can be done for floats and booleans:

 


$variableOne = 4.7545; # This is a float
$variableTwo = TRUE; # This is a boolean

 

It gets a little complicated when it comes to 1 and 0, however. They are both integers but they are also both booleans (TRUE and FALSE respectively):

 


$var1 = 1; # This is equal to TRUE
$var2 = 0; # This is equal to FALSE

 

Get it? Let's move on to strings.

 

Strings

There are two ways to declare strings in PHP, one is using single quotes and the other is using double quotes:

 


$var1 = 'This is a string';
$var2 = 'This is also a string!';
$var3 = '123'; # This is also a string

 

What's the difference? Well, a string is a datatype. And in our strings, we maybe want to put in another variable, be it an integer, string or a float. When you put a variable inside a string, it is converter to a string. In strings with double quotes, you can display variables with interpolation. This is just as simple as putting a variable between the quotes. However, to improve readability, an variables that are interpolated should be wrapped in curly braces ({ }). Example:

 


$number = 17;
$colour  = 'Green';

$string    = "The number is {$number} and the colour is {$colour}";

/*
* The contents of $string is now
* "The number is 17 and the colour is Green"
*/


 

Now let's look at something else. Concatenation. This is used when we want to add variable to a string; append/prepend a variable to another or to append/prepend the return value of a function to a string/variable. Concatenation in PHP is done by using a period ( . ). When concatenating a single quote string, you have to end the string before doing so. Then, you can "restart" the string after, but you need another period. Let's give it a whirl:

 


$name = 'Foo';
$age  = 20;

$string = 'My name is '.$name.' and I am'.$age;

/*
* $string is now
* "My name is Foo and I am 20
*/

 

Which should you use? Well, if you have a string and you know you're going to have variables in it, interpolate with double quotes. For a string where you're not going to have any variables, you should use single quotes.

 

Escaping

"Escaping" (in this context) is when you want to use a a 'special' character inside of a string. For example, if you want to use a single quote inside a single quoted string. In PHP, the escaping character is a back-slash ( \ ). Example:

 


# WRONG
$string = 'I'm walking my dog';


#RIGHT
$string = 'I\'m walking my dog';

 

This can also be applied to double quotes. Also, when you have a double quoted string and you want to include dollar signs, you must escape them. That's the basics of strings!

 

Appending to Strings

We can also append to a string using the ' .= ' operator. Let's look at an example:

 


$string = 'Hello, my name is ';
$string .= 'Jeff';

# String is now "Hello, my name is Jeff"

 

Hello World!

 

So now, we're going to take a look at the echo language construct. This is used to output anything we want to output. It can be an integer, boolean, string or float. If it's a boolean, TRUE will output 1 and FALSE will output nothing. So let's make our first PHP script!

 


<?php
echo 'Hello World!';
?>

 

Turn on your Apache server. Visit the page, and voila! Easy. Let's try this with variables.

 


<?php
$colour  = 'blue';
$number = 3;
$string    = 'I like turtles.';

echo "The colour is {$colour} and the number is {$number}. ";
echo $string;

/*
* Will output:
* "The colour is blue and the number is 3. I like turtles."
*/
?>

 

==

END OF PART ONE

==

 

 

 

 

 



 

 

 

 

 

Part 2 - Operators and Functions

 

Arithmetic Operators

 

There are lots of operators in PHP. An operator, as the name would suggest, is something that performs an operation.

 

In this section, we'll be looking at arithmetic operators. They're pretty straight forward:

  • + - This is the addition operator and is used to add two integer or floating point values together. (x + y)
  • - - This is the subtraction operator and is used to subtract an integer or floating point value from another. (x - y)
  • * - This is the multiplication operator and is used to multiple two integer or floating point values together. (x * y)
  • / - This is the division operator and is used to divide an integer or floating point value by another. (x / y)
  • % - This is the modulus operator and is used to find the remainder when an integer of floating point value is divided by another.
  • ++ and -- - These are used to increase or decrease a variable by 1, respective. (x++, y--)

 

Below are some examples of their uses:

 


$number = 1 + 2; # $number equals 3
$number = 3 - 2; # $number equals 1
$number = 5 * 3; # $number equals 15
$number = 15 / 3; # $number equals 5
$number = 10 % 3; # $number equals 1
$number = 10 / 3; # $number equals 3.3333

##

# Here are some examples of using operators with variables.

$num1 = 10;
$num2 = 20;

echo $num1 + $num2; # Will output 30
echo $num2 / $num2; 

$num1++;
echo $num; # Will output 11

$num2--;
echo $num2; # Will output 19;

echo $num2--; # Will output 18;

 

Let me clarify on the last two: When you use them, they actually change the value of the variable. See:

 


$num = 1;

$num++;

# Is the same as

$num = $num +1;

 

Assignment and Comparison Operators

 

We've already looked at two assignment operators when assigning data to a variable in the for lesson. Those being ' = ' and ' .= '. So I won't be re-covering them. Here is a list of all the assign operators.

 

Now let's look at the comparison operators. So in PHP, we use a single equals sign to assign a variable a value. When we compare things in PHP, the output returns a boolean (TRUE or FALSE) based on whether the condition of comparison was met. I know that sounds confusing, but it really isn't. Let's look deeper into it.

 

If we want to compare two values in PHP, we use the double-equals operator, ==. When we use this operator, it will, it compares two sets of data for their value and not their type. Case matters as well. Let's see some examples:

 


$var1 = 5;
$var2 = 5;

$var1 == $var2; # The result of this is TRUE as they are equal.

$string1 = 'This is a StRing of teXt';
$string2 = 'THIS IS a string of text';

$string1 == $string2; # FALSE

 

An exclamation mark ( ! ) is equivalent to NOT in other languages. It basically returns the opposite boolean from the comparison operator, and this is how we use it with the above:

 


$var1 = 5;
$var2 = 5;

$var1 != $var2; # The result of this is FALSE as they are equal.

 

Now let's look at the strict comparison operator ( === ). This is used to compare values strictly. This means that the value would have to have the same data type and be of the same value for it to return TRUE. Examples:

 


'string' === 'sTring'; # FALSE
'4' === 4; # FALSE

$var1 = 'Password';
$var2 = 'PASSWORD';

$var1 === $var2; # FALSE

 

You can use the NOT with this too. You only use two equal signs:

 


$var1 = 'Password';
$var2 = 'PASSWORD';

$var1 !== $var2; # TRUE

 

PHP is great because it can parse numbers if they're quoted, too. Let me show some examples of this, along with arithmetic operators:

 


$num1 = '23';
$num2 = 4;

echo $num1 + $num2; # Outputs 27

$num3 = '33';
$num4 = 33;

$num3 == $num4; # TRUE
$num3 === $num4 # FALSE

 

There are 4 more operators I'd like to introduce in this less and their meaning will be pretty obvious if you've studied any mathematics: >, <, >=, =<. They are greater than; less than; greater than or equal to and less than or equal to, respectively.

 

Examples:


4 > 5; # FALSE

$num1 = 10;
$num2 = 20;

$num1 >= $num2; # FALSE
$num1 =< $num2; # TRUE
$num1 < $num2; # TRUE
$num2 > $num1; # TRUE

 

--

 

What are these used for? Well, in any programming language, what makes it interesting is comparing values in order to run a piece of code. We will be looking more into this in the next lesson, now that you have a grasp on what these comparison operators are and do.

 

== ==

 

Functions

 

Functions are awesome and a huge part of programming. A function is essentially a piece of code given an identifier (the function name). The piece of code is a function because it can be used again, without the need to re-write the code.

 

PHP has lots of in-built functions to help you out, but you can make your own functions, too.

 

ALL functions in PHP are used by giving their name followed by parentheses (brackets):

 


functionName();

 

Inside a the parentheses, you supply the function with parameters. These are essentially variables that the function can use in order to give an output. We'll learn more about this when we look into writing out own functions.

 

Functions perform an action (or multiple actions) and then return a value. Let's have a look at a few in-built PHP functions. Firstly, let's start with the strlen() function. This function takes one parameter (a string) and the output of the function is the length of the string we entered, hence the name of the function (strlen = str len = string length):

 


$string = 'This is my string';
$length = strlen($string);
echo $length; # Outputs 17

echo strlen('Hello World!'); #Outputs 13

 

Easy right? Let's look at another one. The strtolower() function is a function that takes a string and returns the lower case version of the string. It takes one parameter. A string:

 


$string = 'Apples and Tomatoes and 1234';
echo strtolower($string); # Outputs "apples and tomatoes and 1235"

 

Functions can be outputted, assigned to variables and even concatenated to strings:

 


$string = 'My name is Joe. Joe contains '.strlen('Joe'). ' number of letters';

 

Now let's take a look at making our own functions. The name of your function can be anything and has the same conditions as a variable. You start by writing 'function' followed by the function name and then parentheses. All code inside of your function is to be inside of curly braces:

 


function my_function()
{
    # Code here
}

 

Now you may have notice that I have indented my code. Indenting is a good habit to get into when programming. All code that is inside of these 'curly braces' should be indented. Any code that is 'within' something should be indented. This is done simply by hitting the tab key, however most code editors will indent for you. There are a lot of other ways people use to indent, but I won't go into that.

 

So, anyway, between the brackets, you put your parameters. These are variables that you want to use inside of the function. Whatever they are named when creating the function is the name of the variable inside the function. When calling the function, the variable name does not matter.

 

Variables outside of the function cannot be used. (They can, but we'll look into that later). Any variables you use inside of functions cannot be used outside of functions. Your functions can have functions within it, however, you cannot create a function within a function. We're going to look at the return statement. This used when you want to return fata from your function. Once you return something from a function, any code after will not be run.

 

Let's make a function that takes two parameters and multiplies them together and then dives by 2 and returns the result. Let's name the function 'do_something'.

 


function do_something($numberOne, $numberTwo)
{
    $result = $numberOne * $numberTwo / 2;
    return $result;
}

 

Now let's run that function with sample numbers:

 


echo do_something(1, 2); # This will output 1

 

 

 

==

END OF PART TWO

==

 

 

Greetings, Nicolás™

Posted

What's so awesome about this c/p post which you can find it on every tutorial site. Who really wants to learn php or needs a very good tutorial pm me. I have a very good book which is easy to understand, free ofc.

Posted

What's so awesome about this c/p post which you can find it on every tutorial site. Who really wants to learn php or needs a very good tutorial pm me. I have a very good book which is easy to understand, free ofc.

yeah ok,show me the c/p link!

 

Really impressive.Keep sharing dude.;) :alone: :troll:

thank you
  • 3 months later...

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now


  • Posts

    • Reconstructed the MSNP8 client/server chain in Lineage 2 (from C4 to HFp5) with full protocol capabilities + added Discord integration    Clean MSNP8:       MSNP8 + Discord Bridge:   
    • I'm looking for the GVE code for Luecera2.
    • Recommended seller, I'm using his services. Good luck @Ave
    • https://l2.gamedream.pl/ Update #2 — GameDream Interlude (C6)     This update focuses on Epic bosses, quest chains and overall QoL :cool Highlights: Frintezza access follows a full retail-like chain: Four Goblets → Last Imperial Prince → Journey to a Settlement Retail-like entry requirements restored (scroll + Command Channel) Four Goblets quest is now available in-game Shot visuals synced with attack/skill usage Community Board Premium Shop refreshed with classic Interlude buttons and cleaner tables Epic Raidboss access: Frintezza — 4–5 party Command Channel + scroll + Antique Brooch Antharas — Portal Stone Baium — Bloody Fabric Valakas — Floating Stone Queen Ant / Core / Orfen / Zaken — no quest gates Bug Fixes & QoL: Frintezza quest chain fully fixed TvT rewards — single reward + anti-abuse protection Shots — no double triggering Premium Shop — no blank tabs Mammon NPCs in Giran working correctly Cancel works retail-like (up to 5 buffs removed) Summon Friend fixed with anti-exploit guards YetiBuffer — Saved Buff Profiles (Save / Clear / Restore) PvE — increased aggro range + balance tweaks EXP toggle commands: expoff / expon / expblock Thanks for testing and feedback — more updates coming soon ❤️
    • Hello I would like to offer You my NEW 2026 Updater / Launcher with custom skins.   - UPDATER FEATURES -   1. Performance and Intelligent Resource Management: Smart Disk Detection (SSD/HDD): The updater automatically detects the user's drive type. For SSD/NVMe drives: Launches up to 8-12 concurrent threads, utilizing the full yet optimized connection speed. For HDD drives: Limits the thread count (to 2-3) to prevent computer slowdowns and avoid overloading the drive head. Multi-threaded Downloading: Instead of downloading file by file, the updater downloads multiple files simultaneously, drastically reducing update time. ZSTD Compression: Support for the modern Zstandard compression algorithm (.zst). Files are downloaded in compressed form and decompressed on the fly, saving bandwidth and accelerating downloads. HTTP/2 and Keep-Alive Support: Utilizing the HTTP/2 protocol and persistent connections allows for the instant download of thousands of small files without establishing a new connection for each one.   2. Modern User Interface (UI/UX): Transparency and PNG Graphics: Support for irregular window shapes, allowing for the creation of a unique, modern launcher look. Taskbar Integration: The progress bar is displayed not only in the window but also on the Windows taskbar icon. Built-in News Browser (Optional): The updater features a built-in browser module that displays news/changelogs directly within the launcher (without opening an external browser). Multi-language Support (Optional): Built-in language switching system (e.g., EN/PL/RU, etc.) with dynamic loading of button graphics and text. Animated Buttons (Optional): Dedicated, animated buttons redirecting to Discord, Facebook, YouTube, Instagram, and the website.   3. Technical Features and Application Security: Anti-Dual Run (Optional): The updater checks if the game is already running to prevent file conflicts during updates. Error Diagnostics: Built-in logging system (debug_log.txt) and hardware exception handling (SEH), facilitating the diagnosis of problems for players who cannot run the game. Internal Configuration: Updater settings are stored inside the .exe file, eliminating publicly accessible configuration files.   4. File Categorization (Normal vs. Critical vs. Once): Critical Files: Critical files are verified more thoroughly (via MD5 Hash) even in quick check mode to guarantee stability. Normal Files: Standard game files (textures, models, sounds) are checked depending on the selected mode (Quick vs. Full). Once Files (Overwrite Exclusions): Applies to user configuration files (e.g., Option.ini, User.ini).   5. Check Modes (Verification Algorithms): Self-Update: The updater can update itself before checking game files, allowing for easy deployment of launcher fixes. The updater supports two main operating modes that switch intelligently based on user action: Smart Check (Startup Quick Check): Runs automatically upon updater startup or pressing the START button (unless a full check is forced). Full Check (Full MD5 Verification): Manually triggered by the player via the "Full Check" button. Automatic Update Detection: If a newer version of a file appears on the server, it is automatically detected and downloaded without player interaction. Atomic Updates: Files are downloaded and verified first, and only then saved to the disk. This prevents game client corruption in case of internet connection loss. The entire process takes seconds, even with clients weighing 30GB+. - PATCH BUILDER FEATURES -   1. Professional File Structure Management (Tree-List Hybrid): Directory Tree Visualization: Instead of a flat file list, the Builder displays a clear structure of folders and subfolders. You can collapse and expand entire tree branches, facilitating work with thousands of files. Normal and Critical Division: A clear window division into two main zones: Normal Files and Critical Files. Ghost and Excluded Files Division: The interface visually informs about the status of unchanged files (existing in the previous patch version) and files excluded from the update. Show/Hide Ghosts: With one click, you can hide unchanged files to focus solely on what you are actually sending to players in this update.   2. Intuitive Interaction: Drag & Drop: Full Drag & Drop support. You can grab files or entire folders and drag them between the "Normal" and "Critical" lists. Transfer is intelligent – it moves the entire content of selected folders. Keyboard Shortcuts: Fast workflow thanks to keyboard support: Delete, Enter, Ctrl+A / Ctrl+C (select and copy paths).   3. Advanced Filtering and Searching: Context Search: The search bar works in real-time, filtering the file tree. Type /folder: Searches only within folder names. Type *ex: Shows only excluded files. Standard Typing: Searches files by name.   4. Automation and Security: Auto Self-Update: The Builder automatically detects the updater executable file. Real-Time Statistics: The status bar continuously shows the file count (Normal/Critical), total patch weight (in Bytes/MB/GB), and the last update date. System File Protection: Files marked as "Critical" cannot be accidentally added to the exclusion list – the program blocks such actions.   5. Performance (Backend): ZSTD Compression: The Builder uses the latest Zstandard algorithm to compress files before sending, ensuring a significantly smaller patch size than standard ZIP, saving server bandwidth and player time. Multi-threading: The packing and MD5 checksum generation process utilizes multiple CPU threads, drastically reducing patch building time.   - PRICING - NEW Updater standard price: 79 euro (if You ask for mods, price will change).   - CONTACT - Discord: ave7309   CLICK HERE TO CHECK LATEST TEMPLATES!                         * I have right to REFUSE to take an order. * Supported games: Lineage 2 / Black Desert / MU Online / Tantra / Rohan / Aion / Cabal / Fiesta any more...  
  • Topics

×
×
  • Create New...

Important Information

This community uses essential cookies to function properly. Non-essential cookies and third-party services are used only with your consent. Read our Privacy Policy and We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue..