PHP Tutorial

PHP Tutorial For Beginners

PHP is the most popular server side web programming in the world. Since it had been offered to the public back in 1995, its usage had grown tremendously. Meanwhile, its popularity continues to maintain a stronghold, regardless of the criticism from others who are always there to undermine it.

If you read enough blogs and books, you will find that its popularity emerged from PHP being easy to learn and its ability work well with html and Javascript coding. Regardless of why it became popular, you may want to ask yourself, “Why is PHP right for me?”.

The answer could easily go on indefinitely, but, a few solid reasons why PHP could be right for you are that it has a short learning curve, there is a lot of PHP tutorials, help, and support available online, most affordable web servers have it installed on their system, there is a large code base which makes it easy to find a program similar to one you want to use, and it is very easy to alter other PHP scripts when you have PHP coding skills.

So, now that you may be sold on learning PHP, the next part of this lesson will explain how to start coding with PHP. This basic PHP tutorial will cover basic syntax, printing text, variables and strings, arrays, loops and some insight regarding how to do more fancy stuff with PHP.

If you want to search our library with over hundreds of pages, you can find more PHP tutorials here.


Coding Syntax

When you use or write PHP scripts, the start of a coding can be <?php or <?. In most cases, the starting block uses the long tag <?php. The other method is called a short tag. Some servers will not allow the usage of short tags, but they all allow the usage of the ‘<?php’ tag. It is considered a good habit to code with the long tag so your script has a more ‘universal’ concept. PHP coding is done within files that have the ‘.php’ extension.

Although PHP files must have the “.php” extension, you can add HTML, Javascript, XML and CSS code blocks into your PHP. If you add HTML or other coding like Javascript outside of the PHP tags, The code will be interpreted. However, if you plan to use HTML or JavaScript within PHP tags you will need to create the code using the echo command. Normally, when you use the echo statement a string of text is inserted between single quotes or double quotes.


QUOTES

You use quotes when you want to print words, declare variables and strings. When you want to end the statement, you use a semi-colon. With PHP, you have the option to use single quotes or double quotes. In some instances they have similar behavior, but, not in others.

For example, if you use single quotes around variables, the variable will not be interpreted. But, if you use double quotes, it will. Since a variable could be something new for you, I will show a few examples using single and double quotes with variables and printing statements.

Single Quotes
Declaring a Variable

$variable1 = ‘Hi there’;
$variable2 = ‘John and Paul’;

Printing text
echo ‘Hi there’;

Printing Variables

echo ‘$variable1 $variable2’;

The result of the above statement is the same text that is shown between the single quotes, $variable1 and $variable2. Like I mentioned above, variables within single quotes do not get interpreted.

Double Quotes

Declaring a Variable
$variable1 = “Hi there”;
$variable2 = “John and Paul”;

Printing Text Within Double Quotes

echo “Hi there”;

Printing Variables

echo “$variable1 $variable2”;

As you can see, the output here is much different than the same statement that had used single quotes because it actually prints the data that the variables represent.
Here is one more example that is slightly more creative. It prints variables and text using variables that are outside of quotes and strings of text that exist between quotes.

 echo $variable1.” “.$variable2.” are great guys”;

As you can see, when you echo a variable outside of the quotes, it is interpreted. If they strings of text do not contain variables, they will both output the same results.
Also, this example shown above introduces concatenation. Concatenation uses the period character ‘.’.

When you place the dot in a statement, it can be followed by another variable or a set of quotes. After a set of quotes, you can add another dot and add another variable or set of quotes. If the syntax is not proper, you will see an error when you try to view the page in a browser.

At this point, you should be able to write simple on-liners with PHP and see the output as you expect.
Here are a few more coding examples which could help you understand more about basic PHP syntax.  All the syntax will look different in all of these samples even though they all display the same results.

Sample #1

echo ‘<ul><li>Item1</li><li>Item 2</li></ul>’;
<ul>
echo “<li>Item1</li><li>Item 2</li></ul>”;


Sample #2

<?php
echo ‘<ul>’;
?>
echo ‘<li>Item1</li><li>Item 2</li></ul>’;


Sample #3

<?php
echo ‘<ul>’;
echo “<li>Item1</li>”;
echo ‘<li>Item 2</li>’;
?>
</ul>


PHP Arrays

You won’t get far with PHP without strong knowledge about PHP arrays. An array is a group of options. For example, an array of cars is Ford, Chevrolet, Toyota, Honda, Volkswagen, BMW and Mercedes. An array can written using array(). It contains a list of items separated by commas with values stored in quotes (with the exception of numbers). If an array value contains a number, no quotes are needed.

A tip to understanding arrays is that each item will always have a key and a value. Let’s move on and look over a few arrays to help you know more about them.

An example array of cars is shown below.

$cars = array(“Ford”, “Chevrolet”, “Toyota”, “Honda”, “Volkswagen”, “BMW”, “Mercedes”) ;

Let’s go through the top line of code. The array is called $cars. The car Ford has a key ‘0’ while the car Mercedes has a key of ‘6’. All cars in between have the ordered keys from 2-5. In case you are wondering, numerical keys always start from ‘0’, not ‘1’ like you may expect.  The values are the names of the cars; such as Ford.

Now, here is another example that is equal to the example above, except that we wrote the keys and the values.

$cars = array(0 =>“Ford”, 1 =>“Chevrolet”, 2 =>“Toyota”, 3 => “Honda”, 4 => “Volkswagen”, 5 => “BMW”, 6 => “Mercedes”) ;

The two car samples are identical. Here is how you access a value in the array.

echo $cars[‘0’];

The output from the code about is 'Ford'

Here is another example using the array shown above. It includes a review of some basic syntax we had covered earlier.

echo “My car is a “.$cars[‘0’].”.”;

The output from the code about is 'My car is a Ford'.

More detailed examples and a crash course for PHP arrays can be found at http://lampload.com/PHP-Array-Primer.html.


PHP Loops Tutorial

Loops are another major component of PHP programming that a PHP programmer should learn well. Loops are repeated procedures that you run for a specified number of repetitions. The most common loops you will use with PHP are the for, foreach and while loops.


Simple For Loop

The for loop starts with the word ‘for’. After that, a pair of brackets () holds the conditions and sets a variable. There are 3 main parts within the brackets; the value of a variable(in our case $i). After the variable is set a semi-colon is added. The next criteria(on the other side of the semi-colon) with a condition that says the variable $i is less than 5. It too is separated by a semi-colon. The final criteria is the $i++; this time without a semi-colon. The $i++ is just there to allow for iteration to take place.

In a nutshell, the first value of $i is printed followed by a repeated loop until $i is no longer less than 5.

As soon as $i is not less than 5, there is no more repeated loops.

After the code is added into the round brackets, you add a set of curly brackets for which you can add any desired code.  The example below should make everything clear.

for($i=1; $i < 5; $i++) {
echo $i."<br/>";
}

The output of the above code is the printing of numbers 1-4 on separate lines.


Simple Foreach Loop

The foreach loop is often used to output values from arrays. To make this work, you use the foreach statement and throw an array into it. After you add the array name, you can add another name that your want to use for each element in the array.

Essentially, the foreach statement goes like this …. Foreach my entire array as single value in the array, do this. In the example coming up, you can see an array called $items and it will loop through all values like one, two, three and four.

$items = array('one', 'two', 'three', 'four');
foreach ($items as $item) {
echo $key." ".$item."<br/>";
}

Now that you have the hang of the foreach loop, you may want to try another foreach loop where a key is introduced. Earlier, in the section about arrays, you learned that each item in array has a key and a value.

The main difference with the next loop is that is contains the name of the key(which happens to be $key in this case) and a ‘=>’ which associates an array key to an array value. So, the code below will run a loop for each key and value pair; such as the key ‘First’ and its matching value of ‘one’.

$items = array('First' => 'one', 'Second' =>'two', 'Third' =>'three', 'Fourth' =>'four');
foreach ($items as $key =>  $item) {
echo $item."<br/>";
}

Simple While Loop

While loops do repeated loops as long a s a specific condition is set. Using while loops is very popular with database programming using a database like mySQL.
The code block below will repeat as long as the value of $i is less than 5.

$i = 1;
while($i < 5) {
echo $i."<br/>";
$i++;
}

Here is a glimpse into the future regarding using a while loop with data returned from a MySQL database query. Here is what is going on in the next example. A query is made to select the id, firstname and age from a database table called table_sort. The mysqli_query() function runs the query. Now, the while loops runs for all rows of data within the table. The code within the while loop will run for each row of data that was fetched.

$command= 'SELECT id, firstname, age FROM table_sort';
$result = mysqli_query($db, $command);
while($row = mysqli_fetch_assoc($result)) {
$id = $row['id'];
$user_age = $row['age'];
$user_firstname= $row['firstname'];
echo "<h2>Hi id #".$id."</h2>";
echo "Firstname: ".$user_firstname." | Age: ".$user_age."<br/>";
}


PHP OOP Tutorial Basics

OOP(Object Oriented programming) is more complicated than basic PHP programming that had been discussed in this post. OOP allows you to create objects that use classes, methods and properties. An object is like bundling up a class and being able to use its properties and methods based on accessibility. Methods in OOP are written similarly to regular PHP functions while properties are similar to variables. OOP really allows programmers to keep a tight set of rules within each class. This makes reusing classes very easy.

PHP has gone through various versions; such as PHP3, PHP4 and PHP5. Since PHP4, Object Oriented Programming (OOP) had been available so that programmers could have more coding options. With PHP OOP, programmers can create classes, methods, constructors and more.

Although OOP can seem a little complicated to learn and hand code, you may find that persistence will make this easier. Knowing OOP is valuable since many PHP scripts contain some or the majority of its code with OOP and you will not be guessing about the coding. It also makes it easier to modify an OOP script to suit your needs.
Basic OOP samples can be found here.


MYSQL Database

MYSQL is that most popular database engine that is used with PHP. Under normal working conditions, a PHP programmer will work with MySQL databases on a regular bases. All major PHP scripts like WordPress, Joomla, Magento and thousands more use PHP and MySQL. Information regarding MYSQL can be found here.

Your Bright Future

With years of practice, skill accumulation, and dedication your PHP skills can help open lots of doors. You can seek a regular 9-5 job, freelance, freelance / work fulltime and code as a hobby. Since you have so many options, you can make a switch at any time. For example, some people go the full time route in order to receive steady pay and job security, build a solid resume and build skills which will act as a stepping stone since everyday your skillet grows, so does your worth.

Since a web developer has so many options for self-employment, subcontracting and regular 9-5 work, you don’t have to stay stuck in a job that raises you pennies on the dollar when your skillset and productivity grows 100-500%. As an alternative to a 9-5 setup, your company may allow you to obtain a contract with them and you can work from home. Since your job is really a connection to a web server and done on a pc, you are not confined to a position where your physical being makes any difefernce.

In this era, employers may hire Junior PHP programmers with little experience thinking they are more likely to stay at one job. But, if you develop good PHP code, you are likely smart enough to know your worth in the marketplace.

Everything in life runs its course and always look out for yourself because your needs and interests are unique. Lucky for you, web developers can take their career anywhere since a good laptop is essentially an office.

Regardless of your working needs and desires, there is the right option for you.