PHP – The Basics of the Language

by
Guru

Today I will be talkingย  a bit on PHP’s syntax and constructs. Previously I had given a small introduction on PHP. Now is the time to get your feet wet. Before going even further you should have PHP and MYSQL minimally running on your machine a.k.a localhost (You can go for an elaborate discussion on localhost at wikipedia or stick to my simple description. Refers to your own machine also addressed by 127.0.0.1).ย  I know you are a Geek, you may want to do your own setup but yet, I would recommend you to take a look at integrated packages such as:

  1. Xampp (my preference)
  2. Wamp
  3. EasyPHP

As far as I know personally I have heard of these three packages. There are more out there in the wild. Xampp would be enough for all your development tasks. Please bear in mind these packages are meant only for development purposes. They are not to be used on a live website.

Continuing where I left. Lets talk syntax. uhh, let me remind you coding scripting in PHP is very different from conventional programming. As I say often, PHP has a philosophy, a way of getting things done. ๐Ÿ™‚ Don’t be afraid.

Firstly lets take a look at the basic structure of a PHP script. Each and every script must have a “php” extenstion. For example, “index.php”. You want wonder why? As a matter of fact there are many other extensions that can be used with a PHP script. But for the sake of the world, we will stick to “.php”.

The first and end lines of a PHP script must have proper openings and closing so that the PHP interpreter can do his job.

<?php

?>

Above is the first most used way of opening and closing a PHP script. Simple? Yes, it is simple.

<?

?>

Now, I have shown you a second way of opening and closing a PHP script. I would not advice you to use this particular style. Use the first one. There is yet another style that I will not be showing you. The “ASP” style. Google a bit around if you want to learn more.

Every little snippets of codes goes between the opening and closings. An example follows

<?php

echo “My first ever php script”;

echo “<br/>My second line I am writing in PHP”;

?>

Have you noticed something? Something new I have not yet talked on? Yes? No? What about the way a PHP line ends? If you have noticed the small semi-colon “;”, you got it right. You are Genius. ๐Ÿ˜›

Each and every line in PHP ends with a semi-colon – “;”. Remember this one very well. Many beginners will surely miss it out and be mad at their script yelling syntax error at them. ๐Ÿ˜›

Now, I will be introducing how you declare a vriable and what datatypes are supported.

A PHP variable takes the form ofย  <dollar sign><variable name>, $avariable. Sounds fun? I guess so. But, remeber to adopt a proper standard that you would KEEP thoughout your scripting so as to enable ease of maintenance. ๐Ÿ˜€ Associated with the variables there are some rules that needs to be respected for it to be valid.

  • A variable name must start with a letter or an underscore, “_”
  • A variable name must be made up of alpha-numeric characters (A-Z, a-z, _, 0-9)
  • Any variable name must be one block. No spaces in between. To compensate for this we can use capitalisation and underscore. For example, first_variable or firstVariable

Where to declare a variable is yet another question. PHP is a loosely typed language. Declare variables wherever you need it. At the end of your script? ๐Ÿ˜‰ Urhh, I have not been talking on datatypes. Coming…

  • Boolean
  • Integer
  • String
  • Real
  • Arrays
  • Objects

The above mentioned list make up your the data type list. There is not need to specify the data type while declaring a variable. In short a variable named “username” will be declared as such:

$username;

The correct data type is set automatically by PHP. For example a username will be made up of strings. Assigning a string to the variable will automatically assign the variable as string. But this has one major disadvantage. I will illustrate this with an example.

<?php

$avariable=5;

//perform some operations on $avariable

$avariable=”OMG, something happened here”;

$result=$avariable/5;

?>

The above code snippet shows that you can accidentally assign some value other than that of the expected data type to a variable and PHP will not complain. This will have a direct effect on your operations. Like, we cannot do mathematical operations on a string. These kinds of errors occur when we have hundrends or maybe thousands lines of codes.

Now lets see how we assign some value to a variable.

$avariable=15;

$anothervariable=”This is a string”;

On the left hand side there is the variable name followed by the equal sign “=”, then by your value;

I would have almost missed out something rather important. Lets say you have got a variable name sum keeping a value of 10, now we want to add five to it. How do we do that?

<?php

$sum=$sum+5;

?>

Most probably you would have given me the above as an answer. We have got an alternative way to do this. It applies to multiplication, division and concatenation also.

We will be taking the example of sum again.

$sum+=5;

This one is for the lazy. Well people who want short-hand way of doing things.

Search a bit for concatenation. ๐Ÿ˜›

Do you write codes for yourself to understand? Yes, most of the times this happens. I believe you want to be able to “hint” or comment out your code. But how? Basically there are two ways. One referred as the c-style comment.

Commenting is not only used to make codes easier to understand, but also to help debug and see its state if any part is missing.

c-style comments follows this syntax. /*your comment goes in here, and it can span over more than one line*/

Lets say you have got a block of code and you want to comment it out.

<?php

/*some php codes

goes here

and here also

here also

but they are commented

*/

?>

The above code snippet shows you how to comment a whole block of code. And now? Well, I want to comment out a single line of code. How do I do it? You just need to prefix the part you want to comment with a double forward slash

This way? //php single line of code goes here

Now I am gonna talk a bit on logical operators. No idea about what I am going to talk? These operators are the same as those in Mathematics. Greater than, Less than…

  • Greater than: >
  • Greater or equal: >=
  • Less than: <
  • Less or equal <=
  • Is equal to: ==

Please pay attention to the “equal to”. It takes two equal sign “==” as compared to assignment which takes only one equal sign “=”

Now, we are going to move on to some basic language constucts.

Starting with selection. Basically, selection allows you to make choices given a certain condition. Lets take a real life scenario. You happen to be at a cross-road. Where to turn? Left or right? This small decision that you would take is influenced by a certain condition (reasoning). Selection is based on this same model. I hope you have got the point I were trying to make.

Here is how if..else… works:

if (condition){

//this part will be executed if the condition is true

}else{

//else this section will be executed

}

if…else… gives you the choice to only test for two cases. Do something if condition is true else do the second block of code(s).

Now, lets see the switch. We use the switch if we can to test for more than condition. I will take a dive with this one with an example. Arbitrarily, we consider the sale of apples. The price of an apple decreases as we buy more apples. We are assuming that we would be using “quantum”. Discrete numbers, not range.

On the left hand side we have got the units (number of apples) and on the right hand side the price per apple. Both are imaginary, just for the sake for the explanation.

1ย  –> 5

5 –> 3.75

10 –> 2.50

Now, we have a variable that will get data from an appropriate method ($_GET or $_POST). Let the variable name be, $numapples.

switch($numapples){

case 1:

//perform adequate calculations

break;

case 5:

//perform adequate calculations

break;

case 10:

//perform adequate calculations

break;

default:

//these codes will be executed if none of the above matches

}

The most important part, can you see “break;”? I have highted it in read above. This ensures that only the block of codes corresponding to an appropriate section is executed. If 5 apples are being bought, calculations for 5 apples must be performed.

If you would have used ifs, you would have used the if…elseif…else… structure.

What the switch does, it takes the variable and tests it against all the test cases. And executes the appropriate block of code. Notice, that there is a “default:” which will be executed if none of the above test cases are passed.

Now it is time for some iterations or should we say looping?

The for loop is among the most commonly used as it is real easy to understand and use conveniently in many situations. It iterated throug a block of code a number of times. The number of times is specified by you. The for loop consists of 3 sections separated by semi-colons (“;”) and they are all optional. Omitting them may result in an infinite loop. Be sure to check for this catch.

for ($i=0;$i<10;$i++){

//your code goes here

}

Above is the syntax for the “for” loop. I have color coded the 3 sections. The first one is the starter, this is where you specify where the loop to start at. In my given example I start at zero (0), if the need be you can start at 10. The second section is where your condition goes. As for now we want to loop 10 times, as we start at zero (0), I specified $i < 10, that would make “$i” take values from 0..9 during its existence. From 0..9 that makes 10. This is a simple way to specify condition. The condition part may be more complex/advanced with more checks. The last part is the iterator. After executing the block of code each time, it increments the counter, which in our case is $i.

The while loop iterates though a block of code until the condition has not been met. Lets see the syntax without ado. Btw, are you getting the hang ofย  looping?

while (condition){

//your code goes here

}

Specifically, the looping process will notย  start if the condition(s) are not met in first place. So remember this while writing your condition(s) for the “while” loop. For you to write complex/advanced conditions, they need to be composed. No idea? Well you need to connect two or more conditions and make them one. This is possible with either “OR” or/and “AND“.

  • And is written as “&&
  • Or is written as “||”, do not know where you will find “||”? It is just two pipes without spaces in between. Its locations on keyboard varies so, I will just point you to the key that contains “\”, back slash.

An example of a “complex” condition: “$i>10 && $i<20“. I have just specified a range, that makes it $i should be in the range of 10 and 20. Note: This is also used with “if” and “switch”.

Now, we want to go through the body of the loop at least once. The “do..while” loop does the job. The condition part is the same as the for loop and while loop. So, lets just call it condition. ๐Ÿ˜›

The syntax:

do{

//your code goes here

}while(condition);

Have you observed the tail? Just after the condition part, the “do..while” loop ends with a semi-colon. Down line, do now omit. ๐Ÿ˜€

I have got a last iterator construct to talk about. Before lets talk arrays. Do you know what it is? Yes? No?

Definition: “In computer science, an array is a data structure consisting of a group of elements that are accessed by indexing” (Wikipedia)

Normally an array will consist of a single data-type. But as for now, we are talking PHP. An array is a collection of elements. The elements? Can be anything we talked of earlier! Do you remember the available data types? Make reference if needed. There are two types of arrays:

  1. Indexed are accessed withย  numbers starting at zero (0). This method is quite pain in the arse when working with databases ( We will talk on this one in another article)
  2. Associative is the most programmer friendly. You access an array position using a keyword. A relevant keyword would be far better than using “May”, “Mary” or I don’t know what.

Examples:

  1. $anArray[1], accesses position 1 in array.
  2. $anArray[“username”], accesses the username stored in the array. Quite helpful?

I am not going to confuse you with array as it needs more profound discussion, which I can’t do so at the moment. Read more at php.net

The foreach loop is used to step through arrays. Lets see an example to explain this iterator. Please master this one well as you would be using it quite very often. ๐Ÿ˜€

<?php

$fruits=array(“Apple”, “Banana”,”Grape”); //created an array called fruits containing “Apple” and the rest…

foreach($fruits as $value){

echo “Name of fruit: “.$value;

}

?>

So, how do we read that? The part in blue refers to the array, in our case is $fruits. It steps though the array and places the value in the variable $value. So you can use $value for any kind of manipulations.

This is where I end my journey. Be sure to read more aboout the foreach. There are more complex ways of using it. Learn by yourself. I will be writing how to feed your php script with data later on. See you soon, or should I say subscribe to our feed. ๐Ÿ˜€ Thanks

Categories: Programming
Tags: , ,
  • I still believe that you should do a youtube video. Who reads textual content when learning coding? Anyway, it’s a suggestion.

    It is nice to see regular posts on GS? So, more free time? If yes, fancy watching 2 girls 1 cup again? ๐Ÿ˜› (obligatory inf joke)

  • Not really, having much of time. I completed this what I had started. ๐Ÿ˜€

    I would go for a threesome. ๐Ÿ˜› Fancy it?

  • For maya tutorials we are thinking of using video tutorial. ๐Ÿ˜€

  • InF

    I have a weird voice on videos… :s

    Wonder how a video tutorial would look like ๐Ÿ˜›

  • Yasir

    Au moins, mne ressi aprane sans trap lecture notes lol..

  • It is quite simple for you to understand it.

  • Vikram

    Woooohh….Nice article but that’s too much reading material. I would really like to read your advanced PHP tutorials. Hopefully i’ll get to learn something out of it ๐Ÿ™‚

  • InF

    We are putting in a lot of details, so that even a beginner programmer, who doesn’t know any other language and wants to start with PHP, can get working.

    For PHP novices and pros, I guess you can just skip around if you already know the contents.

    But if you indeed want less details, we can reduce them in future lessons. Depends on what the reader wants. ๐Ÿ™‚

  • I am thinking what advanced tutorial I can write. Any ideas?