Back to Programming Articles

[Part 1] Learning the Basics of Coding
by Pandemikk 30 Mar 2012
Rating: (1 vote - 5.00 average)

Having learned how to code both within the vB3 and vB4 environment, I hope that making this article will provide those interested in learning beneficial advice and teachings within not only a vB environment, but anywhere PHP and MySQL is found. I have no problem answering questions and helping you understand parts as well as updating as needed.

I'm going to split this into (4) sections in (4) different articles: The Basics, Database Interactions, Advanced (includes "good" vs. "bad" code), & Security.

The Basics
I won't go over each and every single function and language construct, but instead provide what I believe to be the fundamentals. A comprehensive manual of PHP can be found here: http://www.php.net/manual/en/index.php

Basic Syntax:
Syntax is very important. The slightest error in syntax will cause the script to error out.

<?php - begins the PHP parasing.
?> ends the PHP parsing.
; -denotes the end of an instruction. Whenever setting a variable, echoing, calling a function, etc, always end with this.
// single line comment.
/* begin multiple line comment
*/ end multiple line comment

Types:
booleans - Simply TRUE or FALSE. Specifying booleans is case-insensitive, however, vB coding standards dictates you use all lower case.

booleans should be used when evaluating any true or false statement.

PHP Code:
$bool false;
if (
$bool)
{
    
$bool true;

While you could assign $bool a value of 1 or 0, using true or false is preferred. Why? Because 1 and 0 are not booleans, they're...

Integers are numbers from negatives to positives. -56, 0, 56, 1092423 are all integers. 56.78 is not an integer- it is a floating point number aka "floats" or "doubles" (more later). It should be noted that integers have a size limit, although it is rare that you'll ever reach this limit because, on a 32bit platform, the limit is around 2 billion. Integers that surpass the limit will be interpreted as floats.

Integers can be used for math, or, in some cases, value checking when booleans aren't enough.

Floating point numbers are like integers, except they include decimals and the mathematical constant e. But for general purposes, you'll recognize floats as -5.6, 5.6, .001, etc. Floats are really useful for things like scores, and any type of math where precision into the decimals is needed.

Strings. The PHP manual says: A http://www.php.net/manual/en/language.types.string.php is series of characters, where a character is the same as a byte. There is no limit on the size of a string besides the amount of memory of the computer running. Strings are most commonly specified with single quotes ' and double quotes ". Double quotes parse variables, carriage returns, new lines, and many others which can be found in a full list in the above link. In strings, the quote that specified the start of a string also ends the strings. You can still use quotes in strings by escaping them with a backslash \.

PHP Code:
$foo 5;

$bar 'This is a sentence. 1, 2, 3, 4, \'$foo\'';
echo 
$bar
The above will print out: This is a sentence. 1, 2, 3, 4, '$foo'

PHP Code:
$foo 5;

$bar "This is a sentence. 1, 2, 3, 4, '$foo'";
echo 
$bar
The above will print out: This is a sentence. 1, 2, 3, 4, '5'

As a side note: echo is a language construct (not a function) that outputs one or more of its parameters. Its parameters are endless and are specified with a comma
PHP Code:
echo 123'four'5.01
Arrays PHP states an array in it is called an "ordered map". A map is "a type that associates values to keys". Arrays are great for looping through because they can have a number of values that would be impossible to guess.

PHP Code:
$array = (
    
'key_1' => 1,
    
'key_2' => 2
); 
Syntax for specifying arrays. You may specify a comma after the last element of an array but it's not good practice to do so. Key casting has its limits: Floats assigned as a key will be casted as an integer (5.2 will become 5), bools will also be casted as integers (true to 1, false to 0), and null values will become empty strings. Objects and other arrays cannot be assigned as keys; it will result in the PHP warning "Illegal offset type". If multiple keys with the same value are given the last one will overwrite the others.

Keys are optional. If a key isn't specified, "PHP will use the increment of the largest previously used http://www.php.net/manual/en/language.types.integer.php key". You can specify the key for some elements and leave it out for others. Variables and $array[key] (see below) can be used to specify the key in $array[key].

PHP Code:
$array = (
    
'key_1' => 1,
    
'key_2' => 2
);

// Outputs 1
echo $array['key_1'];

$key_1 'key_1';

// Also outputs 1
echo $array[$key_1]; 
Accessing array elements.

You may modify array elements the same way you modify variables (covered further down).

Resources are special variables that hold references to external resources (compliments to the PHP guide for that excellent way of explaining them). The most common use of resources within vB is a result of query_read in database interactions. More on that in article 3.

NULL represents no value. It does not represent 0, an empty string '', 0.00, etc. There is only one possible value of NULL: NULL. Unassigned variables and variables that have been unset are NULL.

PHP Code:
// $var is NULL
echo $var;

$var true;
unset(
$var);

// $var is NULL
echo $var
You can think of unset() as making the variable NULL. Unset is a language construct.

On the subject of setting and unsetting variables, the language constructs empty and isset are also highly useful. Empty evaluates to true for empty strings, NULL, 0, 0.0, "0", empty arrays, and false. Isset, on the other hand, can be thought of "is set" and as such only evaluates to true if a variable is set i.e not null.

PHP Code:
if (empty($var) AND !isset($var))
{
    
/* true
AND is redundant because a NULL variable is considered empty and not set */
}

$var '';
if (empty(
$var))
{
    
// true
}

if (isset(
$var))
{
    
// true
}

unset(
$var);
if (empty(
$var) AND !isset($var))
{
    
// true
}

$var = array(=> '0');
if (empty(
$var[0]))
{
    
// true
}

if (isset(
$var[0]))
{
    
// true

Like most language constructs and functions, isset and empty can also be used on array elements.

Type Casting
You can cast any variable a specific type by type casting it.

http://www.php.net/manual/en/language.types.type-juggling.php#language.types.typecasting
The casts allowed are:
  • (int), (integer) - cast to http://www.php.net/manual/en/language.types.integer.php
  • (bool), (boolean) - cast to http://www.php.net/manual/en/language.types.boolean.php
  • (float), (double), (real) - cast to http://www.php.net/manual/en/language.types.float.php
  • (string) - cast to http://www.php.net/manual/en/language.types.string.php
  • (array) - cast to http://www.php.net/manual/en/language.types.array.php
  • (object) - cast to http://www.php.net/manual/en/language.types.object.php
  • (unset) - cast to http://www.php.net/manual/en/language.types.null.php (PHP 5)
$variables vs. CONSTANTS
Variables can be reassigned, modified, destroyed, set, etc. Variables are limited by something called "variable scope". For example, variables within functions, by default, can't be accessed outside of that function and vice versa (variables outside of functions can't be accessed inside them). An exception to this is by using the keyword global. Personally, I recommend avoiding using global when possible as it may lead to some unexpected results (rarely).

PHP Code:
while (true)
{
    
// initialize variable (good practice)
    
$var true;

    
// reassign it
    
$var false;

    
// destroy it
    
unset($var);

While is a loop.

By making the condition "true" the loop will go on forever. No errors will ever occur in this loop; if $var was a constant (which would mean it would be VAR) then an error would occur as soon as we tried to reassign it.

A constants value cannot be changed unless undefined then redefined. Constant naming is the same as variables (no spaces, case-sensitive, can't start with numbers, etc). However, constants, by convention, are usually always all uppercase (makes it easier to identify them).

PHP Code:
define('FOO''bar'); 
A constants value is not limited to a string. It can be any type and no special type casting rules are applied.

Expressions:
Remember what an expression is from algebra class back in high-school? Well if you don't, let me (or rather what I am going to quote) refresh your memory.
Quote by PHP.net
The simplest yet most accurate way to define an expression is "anything that has a value".
PHP Code:
$bool false;
if (
true == true)
{
    
$bool true;

What do you think the value of $bool is? If you're wrong I'll have to rewrite this article.

The if condition is one of the most common expressions. It is the core of any logical problem and even the most advanced coders will use a plethora of them.

PHP Code:
$a 1;
if (
$a == 1)
{
    
// Assigning variables values is an expression
    
$a 2;

What's the value of $a?

PHP Code:
// $i is a common variable name for integers, especially when temporary
function add_one($i)
{
    
$i $i 1;
    return 
$i;
}

$i 0;

$i add_one($i); 
Return is a language construct, inside a function it ends execution (of that function) and returns its argument as the value of the function call. A return without an argument returns null.

Functions are considered expressions, albeit more complex ones. So what's $i? The answer is in the function's name.

Operators:
One thing that surprises me, is the lack of knowledge of some operators. For example, what's the difference between the equal and identical operator? Any decent coder should know this, but I didn't learn this until about a year and half ago.

Operator precedence is much like PEMDAS (American) or BODMAS (English). While there's no exponents or brackets, there are parenthesis, precedence, and left to right ordering.

PHP Code:
// Just like in math, this evaluates to 6 not 10.
$val 5
Arithmetic Operators:
This is just like school. Addition, subtraction, division, multiplication, etc.

PHP Code:
$negative_one = -1;
$two 1;
$zero 1;
$four 2;
$three 3;

// Modulus (remainder of)
$two 3
Assignment Operators:
The most common one is "=". This is not "equal to" like in math. PHP.net says it best:
It really means that the left operand gets set to the value of the expression on the right (that is, "gets set to").
PHP Code:
$ten = ($five 5) + 5
$five is set to 5 within the parenthesis.

With arrays, assigning a value to a key is not done using =, it is done using =>.

There are also further operators that are shorthand for more complex expressions.

PHP Code:
$i 0;

// set $i to 1. shorthand of: $i = $i + 1;
$i += 1;

$var 'Hello';

// set $var to 'Hello World'. shorthand of: $var = $var . ' World';
$var .= ' World'
Do you understand what . does in regards to strings? It's called the string concatenation operator.

Comparison Operators:
http://us3.php.net/manual/en/language.operators.comparison.php

I normally don't just link to the PHP.net version of the article, but going over each of the comparison operators would be too lengthy (char limit). So I will just go over a few of them.

== Equal
=== Identical
!= Not equal
!== Not identical

The main difference between equal and identical is that in identical operators no type conversion takes place. That is to say, if you compared 1 to "1" with ==, "1" would be converted to an integer; whereas if == was === it would not be.

PHP Code:
if (== "1")
{
    echo 
true;
}

if (
=== "1")
{
    echo 
false;

If this code was executed in PHP, your browser would see: 1 (echo outputs true as 1 and false as nothing).

Incrementing/Decrementing
PHP supports pre- and post-increment and decrement.

PHP Code:
$i 0;

// $i is 1
++$i;

// $ is 2
$i++;

--
$i;
$i--; 
$i is now 0 again.

You cannot increment booleans or decrement NULL (nothing happens), but incrementing NULL gives 1.

You can also increment on characters (abc); however, you cannot decrement them.

PHP Code:
$foo 'A';

++
$foo
What's $foo? It's: B

Logical Operators:
  1. AND = and
  2. && = and
  3. OR = or
  4. || = or
  5. XOR = either are true but not both
  6. ! = not
PHP Code:
if (== AND == 1
{
     
// true
}

if (
== OR == 1
{
     
// true
}

if (
== XOR == 1)
{
     
// false
}

if (!(
== 2)) 
{
    
// true

Logical operators are most commonly used within if conditionals.

String Operators:
There's only two of these. The concatenation operator . and the concatenating assignment operator .=

PHP Code:
$a 'Hello';
$b $a ' World';

$c 'Hello';
$c .= ' World'
Are $a and $c equal?

Control Structures:
Control structures have a very self-explanatory name. They allow for the structure of a code to be controlled. And, as such, they can be nested within each other infinitely as long you obey proper syntax. I don't recommend infinite nesting as you will die before ever completing such a task. All control structures are language constructs.

if is one of the most important constructs of PHP and any language really. It allows for conditional execution of code.

The if condition is an expression, and evaluates to a boolean value of true or false. True will execute and false will be ignored.
PHP Code:
$bool false;

if (
0)
{
    
$bool true;

$bool is true.

else is used with an if condition. It executes when the if does not.
PHP Code:
$bool false;
if (
0)
{
     
$bool true;
}
else
{
     
$bool false;

The else statement is not needed here because I initialize the $bool variable. This example is an example of bad coding because it is redundant. Redundancy lowers readability and efficiency without any benefits. More on efficient coding in the third article.

elseif like else, only executes if the original if does not. You can think of elseif as multiple elses. You must end with an else, however, you do not have to end with an elseif.

PHP Code:
$i 2

if ($i == 0)
{
    
// not executed
}
elseif  (
$i == 1)
{
    
// not executed
}
elseif  (
$i == 2)
{
     
// true
}

if (
$i == 0)
{
    
// not executed
}
elseif  (
$i == 1)
{
    
// not executed
}
else
{
    
// true

while is a loop. They are the most simple loops thus they are the fastest loops. They are most commonly used for fetching a mysql result (more in section 2).

While the expression within the while loop evaluates to true the code within the loop will execute. You can think of it as an if conditional that repeats itself (hence "loop").

do-while is the exact same thing as while with one difference: Its expression is evaluated at the end instead of the beginning. This means it always executes at least once.

for loops are the most complex loops, as such they are the slowest and, often, most misused. They have three expression, separated by (if you have been paying attention you should know what would separate these instructions) terminating the instruction with a semicolon ;.

The expressions are evaluated as followed: first, once unconditionally at the beginning of the loop; second, conditionally at the beginning of each iteration; and the third, at the end of each iteration.

Each expression can be empty or contain multiple expressions. An empty second expression evaluates as true and thus the loop runs forever (until your computer pwns u).

foreach loop only works on arrays and objects. They iterate through each element and provide the value OR the key and the value in temporary variables. They are very useful.

PHP Code:
while (false)
{
    
// trollcode - will never execute
}

do {
    
// executes once
} while (false);

for (
$i 1$i <= 10$i++)
{
    
// what's the final value of $i when this loop is done executing?
}

$array = (12345);
foreach (
$array AS $value)
{
    
// $value will go from 1 to 5
}

foreach (array(
=> 1=> 2) AS $key => $value)
{
    
// did you know you could define an array right there? it's perfectly okay to do so

I could have given each loop it's own code segment, but the char limit looms over my head like the Dark Mark.

break ends the execution of the current loop. All, and only, those control structures, in the above code segment can contain a break (with the exception of switch). "break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of." (couldn't explain it better than PHP.net)

break 1 0; is the same as just break;

PHP Code:
while (true)
{
    while (
true)
    {
        break 
2;
    }

Your double indefinite loop has been thwarted by my double break. +5 mana boost.

continue, like break, only applies to loops (and switch). It is used to skip execution of the current iteration and continue at beginning of the condition evaluation. This means, a continue can also end a loop provided the loop will evaluate to false. Like break, it accepts an optional numeric argument: "which tells it how many levels of enclosing loops it should skip to the end of". Like break, 0 and 1 are the same as no numeric argument.

PHP Code:
while (true)
{
     while (
true)
     {
         continue; 
         break 
2;
     }

Your double break has been thwarted by my continue. +10 mana boost.

switch is similar to multiple if conditionals. It has one expression in the beginning, and uses case to compare the value of the expression. If the case evaluation to true code within it is executed. The switch statement will continue executing until there are no more case statements. Use break; (or continue within executed code to end execution for the switch statement. The default statement works like else and executes only if no matches were found to the other cases. break does nothing to default.

PHP Code:
switch (69)
{
    case 
'giggity':
        echo 
'giggity';
    case 
'goo':
        break;
    case 
'default':
        echo 
'Oh, that\'s just nasty!';

It is important to note that switch executes line by line. Just because one case was matched, doesn't mean another case can't.

require and include
Requires and includes are identical, except require on failure will halt script execution while include emits a warning but still execute.

They both include and evaluate a specific file.

PHP Code:
require_once('./global.php'); 
Includes and evaluates global.php, a file vB uses to perform important code.

What's _once do? It check if file is included and, if so, not include it again. Including a file that's already been included will give an error.

vblts.ru supports vBulletin®, 2022-2024