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...

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



×
×
  • Create New...