[Part 1] Learning the Basics of Coding
by30 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.
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
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
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.
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 \.
The above will print out: This is a sentence. 1, 2, 3, 4, '$foo'
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
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.
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].
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.
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.
Like most language constructs and functions, isset and empty can also be used on array elements.
You can cast any variable a specific type by type casting it.
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).
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).
A constants value is not limited to a string. It can be any type and no special type casting rules are applied.
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
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.
What's the value of $a?
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.
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.
This is just like school. Addition, subtraction, division, multiplication, etc.
The most common one is "=". This is not "equal to" like in math. PHP.net says it best:
$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.
Do you understand what . does in regards to strings? It's called the string concatenation operator.
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.
!= 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.
If this code was executed in PHP, your browser would see: 1 (echo outputs true as 1 and false as nothing).
PHP supports pre- and post-increment and decrement.
$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.
What's $foo? It's: B
Logical operators are most commonly used within if conditionals.
There's only two of these. The concatenation operator . and the concatenating assignment operator .=
Are $a and $c equal?
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.
$bool is true.
else is used with an if condition. It executes when the if does not.
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.
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.
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;
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.
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.
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.
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
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?
No members have liked this post.
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 ***
No members have liked this post.
Originally Posted by VidexYou 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.
Rap Battles & Hip-Hop Music - LyricalThreats
No members have liked this post.
I would have to say this tutorial is well written, right to the point and very easy to follow.
Good job Pandemikk
The following members like this post: Pandemikk
thanks a lot....
Egypt News website, latest Egyptian news updated instantly.
No members have liked this post.
Explain distinct and sufficient in the world of coding
And will be available on all other codecs lessons
AdSense revenue sharing 100% - [ Hanan ]
News, egypt : أخبار مصر - Photo, picture : صور
No members have liked this post.
|Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)|
|New To Site?||Need Help?|
All times are GMT. The time now is 06:56.