Register Members List Search Today's Posts Mark Forums Read

Reply
 
Article Options
[Part 1] Learning the Basics of Coding
Pandemikk
Join Date: Jul 2009
Posts: 291

by Pandemikk Pandemikk is offline 30 Mar 2012

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.


Block Disabled:      (Update License Status)  
Suspended or Unlicensed Members Cannot View Code.

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 string 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 \.


Block Disabled:      (Update License Status)  
Suspended or Unlicensed Members Cannot View Code.

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


Block Disabled:      (Update License Status)  
Suspended or Unlicensed Members Cannot View Code.

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

Block Disabled:      (Update License Status)  
Suspended or Unlicensed Members Cannot View Code.

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.


Block Disabled:      (Update License Status)  
Suspended or Unlicensed Members Cannot View Code.

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 integer 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].


Block Disabled:      (Update License Status)  
Suspended or Unlicensed Members Cannot View Code.

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.


Block Disabled:      (Update License Status)  
Suspended or Unlicensed Members Cannot View Code.

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.


Block Disabled:      (Update License Status)  
Suspended or Unlicensed Members Cannot View Code.

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/languag...es.typecasting
The casts allowed are:
  • (int), (integer) - cast to integer
  • (bool), (boolean) - cast to boolean
  • (float), (double), (real) - cast to float
  • (string) - cast to string
  • (array) - cast to array
  • (object) - cast to object
  • (unset) - cast to NULL (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).


Block Disabled:      (Update License Status)  
Suspended or Unlicensed Members Cannot View Code.

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).


Block Disabled:      (Update License Status)  
Suspended or Unlicensed Members Cannot View Code.

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.
Originally Posted by PHP.net
The simplest yet most accurate way to define an expression is "anything that has a value".

Block Disabled:      (Update License Status)  
Suspended or Unlicensed Members Cannot View Code.

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.


Block Disabled:      (Update License Status)  
Suspended or Unlicensed Members Cannot View Code.

What's the value of $a?


Block Disabled:      (Update License Status)  
Suspended or Unlicensed Members Cannot View Code.

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.


Block Disabled:      (Update License Status)  
Suspended or Unlicensed Members Cannot View Code.

Arithmetic Operators:
This is just like school. Addition, subtraction, division, multiplication, etc.


Block Disabled:      (Update License Status)  
Suspended or Unlicensed Members Cannot View Code.

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").

Block Disabled:      (Update License Status)  
Suspended or Unlicensed Members Cannot View Code.

$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.


Block Disabled:      (Update License Status)  
Suspended or Unlicensed Members Cannot View Code.

Do you understand what . does in regards to strings? It's called the string concatenation operator.

Comparison Operators:
http://us3.php.net/manual/en/languag...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.


Block Disabled:      (Update License Status)  
Suspended or Unlicensed Members Cannot View Code.

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.


Block Disabled:      (Update License Status)  
Suspended or Unlicensed Members Cannot View Code.

$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.


Block Disabled:      (Update License Status)  
Suspended or Unlicensed Members Cannot View Code.

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

Block Disabled:      (Update License Status)  
Suspended or Unlicensed Members Cannot View Code.

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 .=


Block Disabled:      (Update License Status)  
Suspended or Unlicensed Members Cannot View Code.

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.

Block Disabled:      (Update License Status)  
Suspended or Unlicensed Members Cannot View Code.

$bool is true.

else is used with an if condition. It executes when the if does not.

Block Disabled:      (Update License Status)  
Suspended or Unlicensed Members Cannot View Code.

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.


Block Disabled:      (Update License Status)  
Suspended or Unlicensed Members Cannot View Code.

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.


Block Disabled:      (Update License Status)  
Suspended or Unlicensed Members Cannot View Code.

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;


Block Disabled:      (Update License Status)  
Suspended or Unlicensed Members Cannot View Code.

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.


Block Disabled:      (Update License Status)  
Suspended or Unlicensed Members Cannot View Code.

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.


Block Disabled:      (Update License Status)  
Suspended or Unlicensed Members Cannot View Code.

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.


Block Disabled:      (Update License Status)  
Suspended or Unlicensed Members Cannot View Code.

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.

Last edited by Pandemikk : 02 Apr 2012 at 01:56. Reason: typo corrections
Views: 5227
Reply With Quote
Comments
  #2  
Old 03 Apr 2012, 05:02
Videx's Avatar
Videx Videx is offline
 
Join Date: Feb 2007
Yet another PHP tutorial. But on vb.org what we really need is something geared towards vbulletin. i.e., How do we write a mod?
Reply With Quote
  #3  
Old 03 Apr 2012, 05:05
AusPhotography's Avatar
AusPhotography AusPhotography is offline
 
Join Date: Nov 2007
Real name: Rick-owner, Kym-admin
Originally Posted by Videx View Post
Yet another PHP tutorial. But on vb.org what we really need is something geared towards vbulletin. i.e., How do we write a mod?
Well this is the basics article and it already introduces some vB specifics -- I assume the remaining three parts will drill deeper.
__________________
www.AusPhotography.net.au a.k.a. AP is a photography forum where members share their photography, photo editing skills and techniques. We run regular photographic competitions; Rick (site owner) and Kym (site tech) using this account
*** Home of the AP fully comprehensive vb4 photographic competition management solution ***
Reply With Quote
  #4  
Old 03 Apr 2012, 05:54
Pandemikk Pandemikk is offline
 
Join Date: Jul 2009
Real name: Jon
Originally Posted by Videx View Post
Yet another PHP tutorial. But on vb.org what we really need is something geared towards vbulletin. i.e., How do we write a mod?
You write a mod using PHP

Making a mod is not the hard part, it's the actual coding in it. Anyone can create phrases and templates, but to actually have files and plugins that do something requires work.
Reply With Quote
  #5  
Old 03 Apr 2012, 17:03
borbole's Avatar
borbole borbole is offline
 
Join Date: Jan 2010
I would have to say this tutorial is well written, right to the point and very easy to follow.

Good job Pandemikk
__________________
I am giving away some of my paid mods for free. Please pm me if you are interested.

My mods.
Reply With Quote
  #6  
Old 01 May 2012, 19:46
abdobasha2004's Avatar
abdobasha2004 abdobasha2004 is offline
 
Join Date: Aug 2008
thanks a lot....
__________________
Egypt News website, latest Egyptian news updated instantly.
Reply With Quote
  #7  
Old 27 Oct 2012, 04:27
Dorgham's Avatar
Dorgham Dorgham is offline
 
Join Date: May 2012
Explain distinct and sufficient in the world of coding
And will be available on all other codecs lessons
Thanks
__________________
AdSense revenue sharing 100% - [ Hanan ]
News, egypt : أخبار مصر - Photo, picture : صور
Reply With Quote
  #8  
Old 07 Nov 2012, 05:29
miner's Avatar
miner miner is offline
 
Join Date: Mar 2005
Real name: Miner
+1 Very useful, thanks.
Reply With Quote
Reply


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
Article Options

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
Forum Jump


New To Site? Need Help?

All times are GMT. The time now is 21:01.

Layout Options | Width: Wide Color: