A beginners guide to programming

I read a lot of tutorials on the Internet. One thing that always fascinates me is the large amounts of tutorials for programmers in the intermediate and advanced stages. Some are on the border of bad programming and I believe this has to do with the poor programming methods learned in the beginning. Simple things like code structure, even though it doesn’t seem like it at first, can drastically improve programming skills.

In this article I plan on sharing some basic things that will help the beginner both in the present and future of his or her career. Lets first cover a few basic concepts. In these examples we will be using PHP, but you can be assured that learning one language can help in future languages; structure and logic are very similar in most languages. When thinking about what the most basic of concepts were for programming, five came to mind:

  • Comments
  • Assignment
  • Output
  • Conditions
  • Loops

Mastering these simple concepts will indeed put you well on your way to becoming a good programmer.

Comments

Comments are parts of the code that the programming language doesn’t look at. These are for most general purposes notes that can be read by a human to help in understanding how a specific function is done. To me comments are one of the most important parts of the program. The first reason for the importance of comments is for yourself later on down the road. If you have a tricky piece of code that you might not remember what does a comment is a great way of leaving your self a little note so that you don’t have to figure out what you were thinking when you wrote that piece of code. The second reason for comments is that you might not be the only one to ever see your code and you want to make sure that other people understand it. I’ve been programming for many years and have seen many others use a wide range of depth in there comments. Some of my friends rarely use comments at all. This is okay when we are dealing with simple lines of code that are easy to figure out, but once complex computations form some help is greatly appreciated. You also have a class of people that want to comment everything. To me this is a waste of time, as if we were to comment everything we would probably just slow people down trying to read our code (especially the advanced users among us). I like to try to find the middle ground and comment particularly complex parts or something that might not be clear at first glance. Lets now look at a PHP example of a few different ways of writing comments. My high school math teacher, Steve Schutts, used to always say “There is more than one way to skin a cat”. This is certainly true with programming:


Now that you have a basic understanding of comments lets move on to assignment. Please note I will be using comments on my code here so that you will have a better understanding of how and when to use them.

Assignment

The first concept you should master if you are going to become a programmer is assignment.  I like to use the simplest example of assignment to help you understand.  When you were born you were assigned a name.  In programming terms that makes you (the nameless baby a variable), and your name that was given to you is the value of that variable.  Perhaps another way of thinking of this is a somewhat reversed algebra.  In algebraic math we strive to find out what is in a variable such as X or Y.  Lets examine this principle:

2x + 2 = 6

In the above equation we try to solve for the value of x. If you have had any algebra at all you'd know the easiest way to do this would be to subtract 2 from both sides and the divide both sides by 2 as shown below:

2x + 2 = 6
-2 = -2
2x = 4
/2 = /2
x = 2

There we have it. The variable x has as value of 4 in it. Lets now take these two concepts (the algebraic equation and the baby naming) and apply them toward a simple program.



As you can see from the above examples in the PHP programming language a naming convention of a $ character (the suffix) and a descriptive identifier (x, baby1_name, baby2_name). These two items together make a variable. The value of these variables can be of several different data types. For now we will focus on three (numeric, string, and array).

Numeric Data Type Variables

Numeric variables can be described as any variable with a numerical value. This value can be -1, 0, or 42 but it has to be numerical. In our above example we have one numerical variable which is named $x. We could have just as easily named this $number or anything else we might have wanted. Numerical variables can also hold simple (or complex) mathematical computations. In the below example we see how some of these simple computations:


As you can see numeric variables can be assigned with any numeric value. We can even add variables together to get results. One thing worth mentioning is that anytime a variable holds a string and is added the string is assumed as the numerical value of 0. We'll cover this more after we talk about string variables.

String Data Type Variables

String variables hold bytes of information. Usually we use these types of variables to hold human readable information. In the case of the baby names we are using string variables. These variables hold the value of the name we give to the baby. Strings data can also be parsed (consider this as the programming language looking to simplify the equation). In PHP we have the ability to control whether a string variable is parsed or not. Lets look at the following examples:


In the above example the first two examples do just as we'd expect them to. We use the . (dot) in the third example to concatinate the string values together making $baby hold the equivalent of 'John Doe' (note the space). On example four we do the same thing again but this time we use the double quote to tell PHP that we wish to parse the value of the first two variables before assigning data. Example number five is a little tricky. Instead of giving the desired output of 'John Doe' like we might expect, the value would simple be assigned as '$baby_firstname $baby_lastname' which would probably not be the results we were looking for unless we were wanting to tell someone about a variable we used in our program. Another notable thing now that we've covered both strings and numeric data types is that there is a difference in the following two lines of code:


The value of $x is numeric. Although 4 is a number the data type of $y is not numeric, it is string. This means that if we were to add the two values together our parser/compiler would have to first convert the value of y to numeric before it could produce the output of 8. This isn't a big problem for the parser/compiler but does use unneeded resources when we could simply start with numeric data types. Lets look at one more piece of code:


What would happen if we were to add $x and $y together? We would get a parse error stating that we have an unexpected string variable when trying to do math. While we might not ever mean to do something like this it is good to have an understanding so that we know what results are yielded in these events. The users of our programs will be better off by not seeing such hard to understand results.

Last on string variables is a simple note. When using string variables that don't require parsing it is faster and more efficient for your programming to use single quotes (') instead of double quotes (") as this doesn't cause the parser/compiler to even check to see if it needs to do something. Next in our variables lesson, the array datatype.

Array Data Type Variables

By now you should have a basic understanding of how variables work. But sometimes we need to store more data in a variable that just a simple name. Perhaps we need a list of things stored in one variable. With that in mind lets examine the array data type:


Arrays are made of two parts. The key and the value of that key. in the first array we have a list of fruits. We have apples, oranges, and bananas; But lets look at how thats ordered in our array.
[0] = 'apples'
[1] = 'oranges'
[2] = 'bananas'
As you can see we have three keys (0, 1, and 2) that each hold a value. Key 1 holds the value of oranges. We might expect that key one would hold the value of apples, but as with most programming concepts 0 is the first number and the first key in this case.

In the second example we would have something very similar for the $numbers array but with numeric values instead of string values:
[0] = 1
[1] = 2
[2] = 3
[3] = 4
[4] = 5
For each of the 5 keys we hold 1 numeric value. We can also see by the third example that we can easily append another key on to this by using brackets []. In this case the value of 6 would be assigned to the 6th key ([5] because of [0]). We also might want to assign the key. This is okay as well:


As you can see by specifying the key we can make a jump and not have to use a specific ordered list. You can also specify a key in order to replace the value of an already declared key. If we were to say $my_array[0] = 44; in our code the value of the [0] key would immediately change to 44 thus replacing the previous numeric value of 1. You might also find it useful to know that keys do not have to be numeric and can be of string type as well. This means that we could do the following:

'Chris Pierce', 'age' => 27);
$info['sex'] = 'male';

In the above we see that we specified the key name as well as the value. This allows us to store information in a little more human readable form. Now our array would look like this:
['name'] = 'Chris Pierce'
['age'] = 27
['sex'] = 'male'
This is extremely useful for when we want to pull a specific type of data from info. Let's look at the next example and assume we still have $info assigned as above:


Now with the simple change of the $what_we_want variable we can pull different information. In the above case we would only pull the name from the array, but by changing line 2 to sex we would only asign 'male' into the $result variable. Now that we have a good understanding of how to assign variables lets look at how to output some of our results.

Output

By using output we can finally start showing our users some of the results of our hard work. This is one of the most useful pieces of our programming especially when we will be showing users our work. It is also one of the most simple concepts we will cover in this lesson:


Reading over the code we see that both print and echo appear to do the same thing. While both do output data to the user, echo is said to be slightly faster due to the fact that echo does not return a value when executed. Print does however return a 1 to signify that the command was executed properly. Lets look at this a bit more closely:


$x is assigned a value of 1 here showing us that the command was executed. Although in my opinion if you ever had it show anything else you'd probably have bigger problems to worry with this will help you to better understand the programming behind the function. echo has another advantage over print in my opinion. echo can take multiple values per line while print can only take one. This means that we can say echo $x, $y, $z; in a program and the values would automatically be concatenated together for us instead of us having to echo each variable on three different lines. While there are other forms of output functions (print_r, sprintf) we will stop at echo and print. Next we start looking at ways to make our programs better with conditions.

Conditions

How many times have you heard something similar to "If you don't pick up your room you can't watch TV tonight". If you have kids its probably way more often than none. This is the simplest form of a condition that I can think of. If you don't pick up your room the result would be no television. If you do the implied is that you would in fact be able to watch television. Lets look at this in php programming terms:



When ran the program would check to see if one condition is met. If the $room variable has a value of 'clean'. If it does then the $watch_tv variable would be assigned with the boolean value of true, otherwise it would be assigned the boolean value of false. Note the use of == instead of a simple =. This is because = is used to assign while == is used to evaluate. === would do the same as ==, but would also make sure that the data type was the same on both sides as well. This means that 4 == '4' would be true while 4 === '4' would return false. For a more detailed list of these Comparison Operators consult the php.net manual. Next lets look at the curvy brackets {} in this script. This allows us to specify what would be done should the condition be met. In the example above we simply assigned another variable for later use. We could have also output information to the user right then. We would do this by putting echo 'You can watch TV'; into the curvy brackets {}. It is also important to note that we could also do both or any other things we might want to do inside the curvy brackets. The else is simply a catch all for anything else, meaning that if the condition above is not met we have something to fall back on. This is especially helpful in the slightly more complex example below:



As you can see we have a simple condition, followed by another condition, followed by the fail safe else condition that is met when nothing else is. This is particularly useful in handling unexpected results (Perhaps a variable is assigned something you were not expecting it to be assigned with). A quicker way for handling simple conditions is the shortif (tertiary) statement. This can be done as follows:



This is the same as above but is referred to as the shortif due to the amount of code required. This is very handy when dealing with short blocks of statements if the condition is met (such as assigning a variable). The biggest problem with the shortif (tertiary) is that users sometimes report that it returns errors with trying to product output with it. This is mostly due to the fact that users try to use echo instead of print inside the statement which as mentioned above is not possible due to the nature of how the function is created.

Loops

Now that we have covered a few of the basics lets move on to loops. Loops are code that is repeated until a certain condition is met. Loops come in very handy when programming. Lets look at a few examples of loops:

The For Loop




The code would result in a count from 1 to 100. Pay attention to the "n" in the script, which causes a newline to be created after every echo. This is in double quotes "" because it does need parsing. You might also see our comparison operator of <= instead of just < which would produce the unexpected result of looping to 99 instead of 100 because the program runs until the condition is not true anymore.

The While Loop




The while loop works similar to the for loop. The main difference is that instead of the loop being executed until a condition is met, the loop is executed while a condition is met. This means we have to use the comparison operator of less than < instead of greater than > on a while loop to keep it true. We would also need to auto increment the loop manually to keep from being caught in an endless loop (A loop that doesn't end as the name suggests). We do this by adding 1 to the value of $x during each pass of the loop. Another important difference in this loop is that it will continue to execute while the expression is true, so depending on the order of the echo and the assignment of the increase is whether the loop counts to 99 or 100. A simple modification of code will help to explain this difference:



As seen from the output of the above code loop produces 99 with new line, the value of $x is increased and then an indented 100 with a new line is printed.

The Foreach Loop

The foreach loop is one of the easiest loops to deal with arrays with. Lets look at a simple array from above:



If we wanted to pull not only one but all of the fruits from the list we could use the foreach loop as follows:



This would produce the output of:
apple
orange
banana
We could also add a simple bit of error checking to the foreach with the help of a built in php function known as count. Let's apply this code below:

0) {
foreach ($fruits as $key=>$fruit) {
echo $key.' - '.$fruit;
}
} else {
echo 'no fruits were found';
}
?>

In the above example you see that we have added a condition to check to see how many keys we had in the $fruits array. If the result is greater than 0 then we loop through the results printing both the key and the fruit which would produce the following:
0 - apple
1 - orange
2 - banana
If count returned 0 the else statement would be activated telling the user that no keys were found in the array.

These basic concepts should help in your programming. Not only with the syntax but also with formatting. Remember that clean code is good code and indents, and comments definitely help. After becoming well versed in the above concepts look at the functions that are already available in PHP using the php.net manual. Questions and comments are welcome.

Join the Conversation

5 Comments

  1. Hi Chris. As your former algebra teacher I have to point out a mistake in the first equation you solved. In the last step 4/2=2.

Leave a comment

Your email address will not be published. Required fields are marked *