Go Back   vb.org Archive > vBulletin Article Depository > Read An Article > Programming Articles
FAQ Community Calendar Today's Posts Search

Reply
 
Thread Tools
[Part 1] Learning the Basics of Coding
Pandemikk
Join Date: Jul 2009
Posts: 292

 

Show Printable Version Email this Page Subscription
Pandemikk Pandemikk is offline 03-29-2012, 10:00 PM

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

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

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/languag...es.typecasting
Quote:
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).

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:
Originally Posted 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:
Quote:
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/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.

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.
Reply With Quote
  #2  
Old 04-03-2012, 03:02 AM
Videx's Avatar
Videx Videx is offline
 
Join Date: Feb 2007
Posts: 3,085
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

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 04-03-2012, 03:05 AM
AusPhotography's Avatar
AusPhotography AusPhotography is offline
 
Join Date: Nov 2007
Location: Hobart & Adelaide .au
Posts: 521
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

Quote:
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.
Reply With Quote
  #4  
Old 04-03-2012, 03:54 AM
Pandemikk Pandemikk is offline
 
Join Date: Jul 2009
Posts: 292
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

Quote:
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 04-03-2012, 03:03 PM
borbole's Avatar
borbole borbole is offline
 
Join Date: Jan 2010
Posts: 2,559
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

I would have to say this tutorial is well written, right to the point and very easy to follow.

Good job Pandemikk
Reply With Quote
Благодарность от:
Pandemikk
  #6  
Old 05-01-2012, 05:46 PM
abdobasha2004's Avatar
abdobasha2004 abdobasha2004 is offline
 
Join Date: Aug 2008
Posts: 541
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

thanks a lot....
Reply With Quote
  #7  
Old 10-27-2012, 02:27 AM
Dorgham's Avatar
Dorgham Dorgham is offline
 
Join Date: May 2012
Location: Egypt
Posts: 69
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

Explain distinct and sufficient in the world of coding
And will be available on all other codecs lessons
Thanks
Reply With Quote
  #8  
Old 11-07-2012, 04:29 AM
miner's Avatar
miner miner is offline
 
Join Date: Mar 2005
Posts: 594
Благодарил(а): 0 раз(а)
Поблагодарили: 0 раз(а) в 0 сообщениях
Default

+1 Very useful, thanks.
Reply With Quote
Reply


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

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT. The time now is 03:47 AM.


Powered by vBulletin® Version 3.8.12 by vBS
Copyright ©2000 - 2024, vBulletin Solutions Inc.
X vBulletin 3.8.12 by vBS Debug Information
  • Page Generation 0.04451 seconds
  • Memory Usage 2,388KB
  • Queries Executed 23 (?)
More Information
Template Usage:
  • (1)SHOWTHREAD
  • (1)ad_footer_end
  • (1)ad_footer_start
  • (1)ad_header_end
  • (1)ad_header_logo
  • (1)ad_navbar_below
  • (1)ad_showthread_beforeqr
  • (30)bbcode_php
  • (5)bbcode_quote
  • (1)footer
  • (1)forumjump
  • (1)forumrules
  • (1)gobutton
  • (1)header
  • (1)headinclude
  • (1)modsystem_article
  • (1)navbar
  • (4)navbar_link
  • (120)option
  • (8)post_thanks_box
  • (12)post_thanks_box_bit
  • (8)post_thanks_button
  • (1)post_thanks_javascript
  • (1)post_thanks_navbar_search
  • (2)post_thanks_postbit
  • (8)post_thanks_postbit_info
  • (7)postbit
  • (8)postbit_onlinestatus
  • (8)postbit_wrapper
  • (1)spacer_close
  • (1)spacer_open
  • (1)tagbit_wrapper 

Phrase Groups Available:
  • global
  • inlinemod
  • postbit
  • posting
  • reputationlevel
  • showthread
Included Files:
  • ./showthread.php
  • ./global.php
  • ./includes/init.php
  • ./includes/class_core.php
  • ./includes/config.php
  • ./includes/functions.php
  • ./includes/class_hook.php
  • ./includes/modsystem_functions.php
  • ./includes/functions_bigthree.php
  • ./includes/class_postbit.php
  • ./includes/class_bbcode.php
  • ./includes/functions_reputation.php
  • ./includes/functions_post_thanks.php 

Hooks Called:
  • init_startup
  • init_startup_session_setup_start
  • init_startup_session_setup_complete
  • cache_permissions
  • fetch_postinfo_query
  • fetch_postinfo
  • fetch_threadinfo_query
  • fetch_threadinfo
  • fetch_foruminfo
  • style_fetch
  • cache_templates
  • global_start
  • parse_templates
  • global_setup_complete
  • showthread_start
  • showthread_getinfo
  • forumjump
  • showthread_post_start
  • showthread_query_postids
  • showthread_query
  • bbcode_fetch_tags
  • bbcode_create
  • showthread_postbit_create
  • postbit_factory
  • postbit_display_start
  • post_thanks_function_post_thanks_off_start
  • post_thanks_function_post_thanks_off_end
  • post_thanks_function_fetch_thanks_start
  • fetch_musername
  • post_thanks_function_fetch_thanks_end
  • post_thanks_function_thanked_already_start
  • post_thanks_function_thanked_already_end
  • post_thanks_function_fetch_thanks_bit_start
  • post_thanks_function_show_thanks_date_start
  • post_thanks_function_show_thanks_date_end
  • post_thanks_function_fetch_thanks_bit_end
  • post_thanks_function_fetch_post_thanks_template_start
  • post_thanks_function_fetch_post_thanks_template_end
  • postbit_imicons
  • bbcode_parse_start
  • bbcode_parse_complete_precache
  • bbcode_parse_complete
  • postbit_display_complete
  • post_thanks_function_can_thank_this_post_start
  • tag_fetchbit_complete
  • forumrules
  • navbits
  • navbits_complete
  • showthread_complete