Backend Development

PHP Tutorial For Beginners

Submitted by Zenith, , Thread ID: 24363

Thread Closed
26-11-2016, 06:16 AM
#1
Installing under Windows

Instructions can be found at http://www.php.net/manual/en/install.windows.php.

Another possibility is to download and run PHPTriad from http://www.phpgeek.com/. This installs the very popular triad of programs: PHP, MySql and Apache. It should be very cool and very easy.

As in all good tutorials, we start with the (in)famous HelloWorld example. Here's the code:
PHP Code:
<html>
<
head>
<
title>Hello World</title>
</
head>
<
body>
<
p>
<?
php
// This is a comment that extends to the end of the line.

/* This is multi-line comment. Comments are ignored by PHP,
 but provide valuable information to people reading the source. */

echo "Hello World!\n";
?>
</p>
</body>
</html> 

You should save this piece of code in a file with the extension .php. If that doesn't work, then try other extensions like .php3 or .phtml. If you can't figure out the right extension, then ask whoever installed the webserver. If that's you, then have a look at the file called httpd.conf - if you're using Apache that is...

It should contain a line that looks like this:

AddType application/x-httpd-php .php

Anyway --- this line informs Apache that files ending with .php are PHP scripts. Thanks go to Jon-o Addleman [email protected] for suggesting that I should write this piece.

Back to the example, which is somewhat silly. But it can be used to teach you a few things anyway.

Most of the code is just plain HTML. Only the part between <?php and ?> is PHP-code. You use either <?php or just <? to start the code and ?> to stop it again. The parser works within these two tags. Between the <?php and ?> you put a number of statements, each of which must be ended by a ; (a semi-colon).

Between the two tags there is a comment and one statement, echo "Hello World";. The comment will be completely ignored, and the statement just prints the string "Hello World" into the webpage, which is then sent to the browser. After the parser has processed the page, the final output that is sent to the browser looks this way:

Code:
<html>





<head>





<title>Hello World</title>





</head>





<body>





<p>





Hello World





</p>





</body>

As you can see, there's no trace of the PHP-code left in the final output. In the following code-snippets I won't include all the HTML code, but remember that you'll have to use HTML if you want your PHP scripts to work on the net. You'll also have to include the right HTML codes in the strings you output from PHP, if you're outputting more than just very simple strings.

You should think of a PHP-script as a normal web page written in HTML, since most of the page is still just plain-old HTML. But between the start- and end-tags (<?php or <? and ?>) the PHP-parsed spices the page up with possibly dynamic content.
Before I show you any more examples I had better introduce to you the different kinds of variables we have in PHP. Variables are what you use to store something for later use. You might want to refer to your age, so it would be nice to define the age only once, and then just refer to it later. When your age changes, you just update the definition of your age, and then all other calculations that refer to the age are also updated. All the names of the variables must start with the $ character. After that there must be a letter. The rest of the name can consist of both letters and numbers. Here are three examples of valid names for a variable: $name, $address2 and $colour_30. As you can see, you can also use the _ (underscore) character in your names. It is often used as a replacement for spaces, since they are not allowed.

To use a variable you have to assign a value to it. It is done this way:
PHP Code:
$name 'Martin'
The name of the variable is on the left of the = sign and the new value of the variable is on the right. Here we assign the value of 18 to the variable $age: $age = 18;
There are several different types of variables. You have already met the integer and string types. Lets start with the integer type.
Numbers

Dealing with numbers is easy with PHP. You can just use them as you like. All the normal rules about precedence apply, so you can write something like this:

PHP Code:
$a 4;
$b 7;
$c $a $b // This is evaluated as 2 + (3 * 4) + (5 * 7) = 49 

As you can see, everything works as you would expect. Any variables are automatically substituted with their values. This is done before the new value is stored in the variable on the left side of the =-sign. This means that you can do something like this:

PHP Code:
$a 5;
$b 10;
$a = ($a 5)/$b// Evaluated as $a = (2 * 5 + 5)/10 = 1.5 
Strings

To assign a string to a variable, you must use quotes. You can choose between single quotes (') or double quotes ("). The kind of quote you should choose depends on the string you work with in a given situation. There are some differences between the two types of quotes, which the following code should demonstrate:

PHP Code:
$first_name 'Martin';
$greeting1  "Hello, my first name is $first_name.";
echo 
$greeting1;
$last_name  "Geisler";
$greeting2  'Hello, my last name is $last_name.';
echo 
$greeting2
This code produces the following output:

Hello, my first name is Martin.





Hello, my last name is $last_name.

"Why was it only the first string that worked properly?", you might ask. The answer is that when using double quotes, PHP performs what is known as variable-expansion. That means that PHP expands (substitutes) $first_name with it's value, just as you saw it when using numbers. The result is that the string stored in $greeting1 is "Hello, my name is Martin." (the quotes are not part of the string stored in $greeting1). When assigning to $greeting2 using single quotes, PHP doesn't substitute any variables and $greeting2 ends up with "Hello, my last name is
PHP Code:
$last_name.". 

But there's more magic with the double quotes. They will also expand other special characters, such as newline-charecters (\n). This mean that the following string:
PHP Code:
echo "Martin\nGeisler"
will look like this in the source of the page:

Martin





Geisler

You've met the echo statement before (in the Hello World example) and it just outputs the string after it to the webbrowser. As I said earlier there's no trace of the PHP code, but notice that there's a linebreak between the two words. (The linebreak can only be seen in the source of the page, because the webbrowser treats the linebreak as a normal space.) You should also notice that there's no space before or after the \n-character. Because you use the \-character to indicate that the next character is special, you have to write \\ when you want to have a single \. The backslash (\) is called an escape-character, since it makes the characters escape from their normal role. The escape-character also has to be escaped.

If you want to have a $-charactar in a string enclosed in double-quotes, you'll need to escape it, or else PHP will look for a variable, since all variables start with a $.

This string will give you a little problem:
PHP Code:
$name "Martin "gimpster" Geisler"

If you try it out, you'll get an error. That's because the parser expects the string to stop after the second double quote, just before the word gimpster. The rest of the line is just garbage to the parser so it complains loud. Perhaps it would help if we escaped the double quote? Exactly! The following string is correct:
PHP Code:
$name "Martin \"gimpster\" Geisler"

The same applies if we had been using single quotes throughout the string. But there's another way to solve the problem. You could quote the string with single quotes and then use as many double quotes within the string as you would like. Or you could do the inverse, and enclose the string in double quotes and use single quotes in the string. This solves a problem you would have when outputting HTML-code with lots of double quotes:
PHP Code:
echo '
<a href="mailto:[email protected]">
 <img src="image.gif" width="16" height="16" alt="me" border="0">
</a>'

If we had quoted the string with double quotes, we would have had to escape all the other double quotes. But on the other hand, in the string above PHP wouldn't do any variable-substitution. Also, the escape-characters will not be understood, so you can't write \n in a string enclosed by single quotes. Instead you can put the newlines directly into the code, as I've done in the example. The final output will still contain those newlines.

It's only when you're evaluating expressions (such as in assignments and echo statements) that the difference between single and double quotes comes into play. After the assignment is done, you wont be able to tell how the string was produced. Consider this code:
PHP Code:
$first_name 'Martin';
$last_name "Geisler";
$var1 "$first_name $last_name";
$var2 'Martin Geisler'

The two variables $var1 and $var2 will both contain the string Martin Geisler after the evaluation, without any sign of all the different kinds of quotes that were used in the construction and PHP will not make any distinction between the values stored in the two variables.

If you want to concatenate (add together) two strings you use the .-character (a dot or full stop) like this:
PHP Code:
$first_name 'Martin';
$last_name 'Geisler';
$full_name $first_name.$last_name
Now $full_name will contain the string "MartinGeisler". That's probably not what you wanted, it would be better with a space between the two words. To do this, you execute the following code: $full_name = $first_name . ' ' . $last_name;

Notice that the space between the variable-name and the dot is ignored --- it's the string with the space that's important. You use the dot (full-stop) each time you have two strings that you need to put after one another.

But you've also seen how this could be solved using variable-substitution. This is often easier to read, just remember to use double-quotes around the string. So this code gives the same result:
PHP Code:
$full_name "$first_name $last_name"

When using variable substitution you might run into a little problem. The problem occurs when you want to substitute a variable in a string and have text immediately after the variable. You have to delimit the name of the variable somehow. Using curly braces is the solution as shown in this code:
PHP Code:
$noun 'car';
echo 
"A $noun, two ${noun}s"

Here we're playing with English words in plural form. The first occurrence of $noun is substituted correctly, even when it's followed immediately by a comma because you cannot have a comma in the name of a variable. But you could certainly have a variable called $nouns, so we have to use curly braces to indicate that we want the variable called $noun and not some nonexistent variable called $nouns.
Arrays

Arrays are a single variable that can hold a number of different values at the same time. To access the different values you specify them by using brackets after the name. It works like this:

PHP Code:
$name[0] = 'Martin';





$name[1] = 'Geisler'

(There's no syntax hightlighting in the above example because it involves square brackets with numbers in them, which is also used for footnotes in PhpWiki. So some of the following examples will be in plain black & white.)

Now we have made an array, and filled in the two first slots. Notice that the numbering starts at zero and not one. We can recall them like this:

PHP Code:
echo $name[0] . ' ' $name[1]; 

If you don't care which slot you get when you assign to an array, then use a pair of empty brackets after the name:
PHP Code:
$name[] = 'Martin';
$name[] = 'gimpster';
$name[] = 'Geisler'
This filled the first three slots of the array, numbered 0, 1, and 2. When you want to retrieve the information again, you must specify which slot you want access to. But you can also identify the different slots by name. This makes everything much more readable and easy to understand:
PHP Code:
$personal_data['first name'] = 'Martin';
$personal_data['nickname'] = 'gimpster';
$personal_data['last name'] = 'Geisler';
$personal_data['age'] = 18;
echo 
'Hello ' $personal_data['first name'] .
  
'! We know that you are ' $personal_data['age'] .
  
' years old.'

Notice how I broke the last line to make it shorter and how I used the dot operator to glue the strings together with the variables. The parser will ignore all whitespace, and the result is:

Hello Martin! We know that you are 18 years old.

Also note how I split the string up into its individual pieces. This is often the easiest way to deal with associative arrays. Another possibility is to use variable substitution with curly braces like this:
PHP Code:
echo "Hello {$personal_data['first name']}! " .
  
"We know that you are {$personal_data['age']} years old."
This code gives the same result. You can put complex expressions inside such a set of curly braces. This includes accessing elements in multidimensional arrays and object properties.

Please do use descriptive names for the slots in your arrays. It makes the code much more clear, and helps to indicate what the different slots are intended for.

Now that we have seen how to assign values to variables, let's have a look at the different control structures there are in PHP:

You use control-structures to control the flow of execution through your program. If you didn't have any of these control-structures, all your scripts would always do the same. So let's get on with it.
The if-statement

We start with the if-statement. You use the if-statement to execute different parts of your script based on the truth-value of an expression. The expression could be something like $a > 5. This tests to see if the variable $a is greater than 5. If so, the expression is true, and the next part of the if-statement is executed. If the expression is false, then the optional else-part of the if-statement is executed. In a script it would look like this:
PHP Code:
if ($a 5) {
 
$b $a 10;
} else {
 
$b $a 2;


If the part between the parenthesis, (), is true, then the statements between the first pair of curly braces, {...} is executed. Else the part in the curly brackets after the else keyword is executed. You don't have to provide a else-part, if you don't then nothing will be executed if the test fails.

You can have all kinds of statement between the parenthesis and the curly braces. PHP is a language where almost every statement has a value, a value that can be used together with other values to build big expressions.

Take an assignment for example. The statement $b = $a actually has a value, namely the value of $a. This means that you can use this value in another assignment, like this:
PHP Code:
$c = ($b $a); 

The assignment in the parenthesis has the value of $a which is then assigned to $c. You can actually drop the parenthesis; the result is the same: all three variables have the value of $a. This allows you to understand a statement like this:
PHP Code:
/* Initialize counters: */
$i $j $k $l 0

To compare the value of a variable up against other variables of numbers, you have a number of different comparison-operators:
Code:
Operator  Meaning
==  Is equal to
!=  Is not equal to
<  Is less than
<=  Is less than or equal to
>  Is greater than
>=  Is greater than or equal to
&&, and  The first and the second is true
, or  The first or the second or both is true

(Note: problems with the WikiMarkup; you actually need to use || and not as the or operator.)

Using these operators you can construct every Boolean expression you'll ever need. Take for example the following if-statement:
PHP Code:
if ($a <= $b && ($array[$a] <= $array[$b] || $array[$a+$b] > $array[$a-$b])) {
/* Do something useful - this is a comment, it won't be executed */


This if-statement first tests to see if the variable $a is smaller or equal to the variable $b. If true, the next part is executed to see if it is also true. This happens because we're using &&, which means that the first statement and the second statement should be true.

The second part uses $a and $b as indexes in an array. If the first part is true, then the second part won't be executed. We're just interested in whether the entire test is true, which it is, if either the first or the second test is true. So there's no need to evaluate the second test, if the first is already true. This means that you can execute the following statement:
PHP Code:
mysql_connect() or die('Could not connect to the database!'); 

The function mysql_connect() tries to make a connection to a MySQL database. It returns true if it was able to make a connection. PHP evaluates the line as a Boolean expression. That means that it starts by executing mysql_connect(). If that returns true, then PHP skips the next statement, because we used or. The second statement makes PHP stop with an error message, if the first statement fails. As you can see, you can make it as complicated as you want.

There are other control-structures:
The for-loop

The for-loop is useful when you need to have the same task repeated a number of times. The for-loop works by first initializing a variable, then performing a test, and then - if the test is true - executing some code. After that code has been executed, additional code is run to increment the variable and then execute the main code again. An example will probably help:
PHP Code:
for ($i 0$i 10$i++) {
 echo 
$i;


"Hmm, now he introduced several new things again" you might think. And you're perfectly right. First, let's have a look at the for-loop.

It first assigns a starting-value of 0 to $i, then it checks to see if $i is smaller than 10, and, if so, the echo-statement is executed. At the end of an iteration, (one pass of the loop) the $i++ statement is executed.

This statement is a shorthand of $i = $i + 1;. It simply increments the variable i by 1. Similarly, you could write $n--; that would decrement the variable $n by 1.

The main code is executed while $i is less than 10, so our little for-loop simply prints the numbers from 0 to 9 into our webpage.
The while-loop

The while-loop is very similar to the for-loop. It works like this:
PHP Code:
while (something is true) {
 
some statements

It is used when you don't know in advance how many iterations you'll need. If you look close, then you'll see that each for-loop can be made into a while-loop and that each while-loop can be made into a for-loop. This is because a for-loop like this (where a, b, c, and d are statements):
PHP Code:
for (abc) {
 
d;


works completely like this while-loop:
PHP Code:
a;
while (
b) {
 
d;
 
c;


You'll often see a while-loop being used to run though an array like this:
PHP Code:
while (list($key$val) = each($array)) {
 echo 
"<p>$key => $val</p>\n";

The condition in the while-loop uses several functions and an assignment. Each time the function each() is called, it returns an array with the key and value from $array. When there are no elements left in $array, each() returns false - this is what makes the whole condition false and makes while-loop stop.

The list() function can be used on the left side of an assignment to extract values from an array. You can use list() like this, although it would be much easier to assign the variables one at a time:
list($a, $b, $c, $d) = array(1, 2, 3, 4); // $a == 1, $b == 2, $c == 3, $d == 4

So the condition in the while-loop prepares $key and $val for the body of the loop. When all key-value pairs have been examined, the loop terminates because each() return false, which then becomes the value of the assignment, and therefore the value of the condition.

After you've run through the array like this, each() will return false if you use it on the same array. You'll have to call reset($array) to make each() start from the beginning again.

Here is an example with reset() and each() that will build a table that shows the keys and values of an array:
PHP Code:
$array = array('Foo' => 42,
       
'Bar' => 3.14,
       
'Baz' => 2.71);

// Start the table
echo "<table>\n";
// Print the first row with headers
echo "<tr>\n";
echo 
"  <th>Key</th>\n";
echo 
"  <th>Value</th>\n";
echo 
"</tr>\n";

// Ensure that the each() function starts from the start:
reset($array);
while (list(
$key$value) = each($array)) {
 
// Print a single row
 
echo "<tr>\n";
 echo 
"<td>$key</td>\n";
 echo 
"<td>$value</td>\n";
 echo 
"</tr>\n";
}
// End the table
echo "</table>\n"

This code will produce a table like this one:
Key Value
Foo 42
Bar 3.14
Baz 2.71

The important thing for you to notice in the above code is the way HTML tables can be built up in PHP. Tables in HTML start with the opening tag, and then comes any number of rows, each row consists of any number of cells. Finally you close the table again.

So when building HTML tables using PHP, remember that they always start in the upper left-hand corner (the cell that says "Key" in this example) and then continue to the right along the same row: then come the rows below in the same way, left-to-right, until you finally end up in the lower right-hand corner (that's the cell that says "2.71" here).

Whenever you need to use a certain piece of code over and over again, it is very useful to put it in a function. By putting your code into functions, you make the code easy to reuse. Whenever you locate an error in your code, you only have to fix it once: in the function. Using functions also makes your code easier to read and understand, especially when you choose sensible names for functions. Let's start with a simple function:
PHP Code:
function foo($arg) {
 if (
$arg 10) {
  echo 
"$arg is smaller than 10";
 } else {
  echo 
"$arg is greater than or equal to 10";
 }

This piece of code declares a function called foo. It takes one argument (that's the bit between parenthesis called $arg above), and it echoes different things, based on the value of that argument. You "call" the foo function lower down the page, in your other code like this:
PHP Code:
foo(15); /* Echoes "15 is greater than or equal to 10" */ 

Isn't that simple? You can also make functions that don't have any arguments, just add an empty pair of parenthesis after the name of the function, both when you declare the function and when you use it.

If your version of PHP is below 4 (use the function phpinfo() to learn all sorts of things about PHP) you have to declare your functions before you use them. That isn't necessary with version 4 and above. You really should use at least version 4, as it is the latest at the time of writing.

You often need your functions to return a value you can use in your programs, and here is how to do that: simply use the return statement.
PHP Code:
function bar() {
 return (
time() - mktime(0001211982))/86400;

This function has no arguments and it returns the number of days since the 21st of January, 1982 (my birthday :-) It uses a number of different built-in functions to get the time now, and then subtract the time I was born, and finally divide the time with 86400, the number of seconds in a day.

Under UNIX all times are measured as the number of seconds since the beginning of the Epoch, which was in 1970. So when you deal with times as I just did, you are just dealing with rather large integers (around 950,000,000). That makes it very easy to find the time between two events.

Note that before we return the number, we could round it with the round()-function, which will round the number to an integer: more on round() below!

In the body of the page you call into action that bar function like this :
PHP Code:
$days_ages bar(); 

If instead you wanted to round the floating-point number to a certain number of decimal places, then it's easy to make your own function:
PHP Code:
function smart_round($float$dec) {
 if (
$dec == 0) {
  return 
round($float);
 } else {
  return 
floor($float pow(10$dec) + 0.5) / pow(10$dec);
 }
}

$a smart_round(2.3172); /* Now $a is equal to 2.32 */ 

This smart_round function returns $float rounded to $dec decimals. The php-function:round has been changed in recent versions of PHP to allow the use of that second, precision, $dec argument.

A new feature in PHP4 makes it possible to use an entire file as a function. This makes it possible to save all your really cool functions in different files, and then use them in different scripts. This expands on the concept of code-reuse, as I talked about earlier. All this is possible thanks to the improved include language-construct: include() can now use a value returned from an external file, instead of calling a function declared in the same file.

Let's look at this in action! We have the file foo.inc which we want to use within the file script.php. This is the code for foo.inc:
PHP Code:
<?php
/*  You must write the included files within PHP,
 in other words within <?php and ?> tags. This is because the assumption is always made that
 included files are not part of any PHP code.  */

return (time() - mktime(0001211982))/86400;
?>

Then you could write the following in script.php:
PHP Code:
$days_aged = include('foo.inc'); 

That works just like the other example, except that you have reused the code from an external source.

Source
- http://www.enginsite.com/
- http://codesamplez.com/
- http://www.php.net
- https://en.wikipedia.org/wiki/PHP
- http://www.codecademy.com/
- http://phpcodechecker.com/
- http://google.com/

[Image: Yp8ZHSk.gif]

RE: PHP Tutorial For Beginners

#2
Damn nice tutorial. In my opinion it could be improved if you added titles to separate each point ie titles for "Strings" / "Variables" and so on. I will give this more of a read a bit later though. Thanks for posting this.

RE: PHP Tutorial For Beginners

#3
Very nice tutorial for us beginners. Thanks for this Smile

RE: PHP Tutorial For Beginners

#4
nice tuto.. i try to learn php in mi free time... thx for this

RE: PHP Tutorial For Beginners

#5
Very useful tutorial for the beginners.

RE: PHP Tutorial For Beginners

#6
Really dope tutorial, well done zenith Smile

RE: PHP Tutorial For Beginners

#7
Wow.. it's very informative... but do you knw what technologies are used in this forum... like php mysql and ....?

RE: PHP Tutorial For Beginners

#8
Thanks for you tutorial !

RE: PHP Tutorial For Beginners

#9
Thanks for the share man it definitely helped

RE: PHP Tutorial For Beginners

OP
#10
12-01-2017, 03:26 PM
testaccount1 Wrote:
Wow.. it's very informative... but do you knw what technologies are used in this forum... like php mysql and ....?

The first link is a download link to what you can use.

[Image: Yp8ZHSk.gif]

Users browsing this thread: 2 Guest(s)