|
|
Php - The Basics - Learn the basics of PHP | ||
Discussion by Spectre with 44 Replies.
Last Update: November 15, 2005, 6:52 pm (View Latest) | Page 1 of 2 pages. | ||
![]() |
|
|
This tutorial should help get you started if you are just setting out into the big bad world of eb development. I have been coding in PHP for a little over a year now, and have worked on several large projects in the language - but whilst I certainly don't know everything about it, I would like to share some of the basics that hopefully will give you a bit of a kick start.
Just a few quick notes to begin with:
PHP can be placed in any plain-text file, but that file has to be passed to the PHP engine. This usually requires that the web server be specifically instructed to do so, because it isn't going to automatically figure out what to do. The PHP engine ignores everything outside of the <? ?> tags, sending it directly to the client as output. This enables you to embed HTML within a PHP script, allowing for maximum power when it comes to delivering web pages to users.
The PHP manual is an invaluable tool of reference for any PHP programmer, regardless of their experience or skill. I find myself constantly referring to it when I forget the exact sytnax of a function or when debugging is getting me down.
This tutorial covers:
+ Functions
+ Constants
+ if...then..else
+ Switch() structure
+ While() and For() loops
Functions
Functions are what carry out all the operations that need completing in order to fulfill the task(s) you designed your script for. PHP allows you to design your own functions, which can call other functions, process and modify data, and anything else you would want them to do.
Functions can do whatever you want them to, and are an essential part of developing large scripts or applications which incorporate a large number of scripts. They allow you to specify a set of instructions which can be repeated at any time during the execution of your script without having to re-write them all - instead of including many identical lines of code in order to carry out the same set of instructions again and again, you simply call the function.
Defining a function is easy, and you can specify which (if any) arguments are passed to it - and whether or not those arguments are optional. An argument is treated as a variable, and that variable is assigned the value of the argument. Multiple arguments can be specified for each function, but they aren't required. If an argument is optional, you can specify the default value that argument will have if it is not assigned when calling the function.
CODE
// Standard function definition with no argumentsfunction MyFunction() {
}
// Function definition with a single required argument
function MyFunction( $argument ) {
echo $argument;
}
// Function definition with multiple required arguments
function MyFunction( $argument1, $argument2, $argument3 ) {
echo "$argument1, $argument2, $argument3";
}
// Function definition with single optional argument
function MyFunction( $argument = '' ) {
// Note that '' will be the default value of $argument if no value is specified.
// '' can be changed to anything of any type ('string',1,2,3,FALSE,array(),etc).
if( $argument == '' ) {
echo 'No argument.';
} else {
echo 'Argument.';
}
}
In the above example, the function MyFunction() is declared. This means that anywhere in the script that defined the function - as well as any other scripts used via include() or require() - can access this function whenever they need to.
A custom function can return a value if required, but it doesn't have to. The value is returned by using the 'return' statement, which is optionally followed by a variable or value which will be the result of the function. A return statment results in the immediate termination of that particular function, but it does not terminate the entire script - if exit() or die() are called from within a function, the entire script is halted, but the return statement only affects the function it is within.
CODE
// Returns nothing - simply exits the function.function MyFunction() {
return;
}
// Returns the boolean value TRUE
function MyFunction() {
return true;
}
// Returns a substring of the argument
function MyFunction( $argument ) {
return substr($argument,0,3);
}
Constants
A Constant is similar to a variable, however, it's value remains constant (hence the name) - that is, it doesn't change. Constants are very useful for use in scripts where the same value will need to be accessed many times without changing. phpBB, for example, defines a constant 'IN_PHPBB' with the boolean value TRUE, which it then checks for in other scripts so that it knows it is being accessed correctly.
Constants are defined using the define(constant,value); function, and unlike variables, are used without the $ symbol prefix:
CODE
define('CONSTANT','This is a constant');echo(CONSTANT);
Like variables, constants are case sensitive, meaning that 'CONSTANT' is different to 'Constant'. Once declared, their value cannot be changed and they cannot be 'destroyed' (eg. via the unset() function).
if...then..else
If statements are something that simply cannot be avoided or ignored in programming - in PHP or otherwise. They allow you to ensure that everything is running exactly the way it is supposed to be - and if it isn't, then you can do something about it.
A basic if statement consits of a condition and a statement or series of statements. The condition is evaluated first, and if it returns TRUE, then the statements are processed. You can also use the Else and ElseIf statements to instruct the script on what to do if the initial condition is not met.
CODE
// A simple if statementif( condition )
echo 'True';
Now whilst the condition must be TRUE, that does not at all mean that it must be a boolean value being compared - it simply means that the overall condition must be true. For example, if( $variable > 3 ) would return TRUE if the value of $variable was larger than 3, but FALSE if it were 3 or below. It is important to remember that a double equals sign is used for comparison, as opposed to a single equals symbol used for assigning a value.
If only one statement must be processed as the result of a condition, then it can simply be placed on the next line underneath the if statement - however, if you need to specify more than one statement, you can enclose them in curly braces.
CODE
// A simple if statement with more than one resulting statementif( condition ) {
echo 'First statement.';
echo 'Second statement.';
echo 'Third statement.';
echo 'And so on.';
}
// Using Else
if( condition ) {
echo 'True';
} else {
echo 'False';
}
// Using ElseIf
if( $variable > 100 ) {
echo 'Over 100';
} elseif( $variable < 25 ) {
echo 'Under 25';
} else {
echo 'Between 25 and 100';
}
Get the picture?
More than one condition can be evaluated within a single if statement. You can either require that all conditions meet the same result, or that one condition meet one result or another condition meet another result.
CODE
// Requires that all conditions are trueif( $variable1 == 123 && $variable2 == 'xyz' ) {
statements;
}
// Requires that either condition be true
if( $variable1 == 123 || $variable2 == 'xyz' ) {
statements;
}
// Any number of conditions can exist
if( condition1 || condition2 || condition3 || condition4 )
if( condition1 && condition2 && condition3 && condition4 )
// Required condition blocks can be placed in brackets
// The following would result in true if both condition1 and condition2 were true, or if both condition3 and condition4 were true, or if all conditions were true.
if( ( condition1 && condition2) || ( condition3 && condition 4 ) )
It is also possible for the condition to be evaluated as false - that is, it equals TRUE only if the requirement is FALSE. This is done by using the exclamation mark (the !) preceeding the condition. Kind of hard to explain, so here's an example:
CODE
// If $variable is not equal to 3...if( $variable != 3 ) {
statements;
}
Functions can be included as a part of the condition as well. The result of the function or the value that it returns is what is used as part of the evaluation.
CODE
// If MyFunction($variable) is equal to 3...if( MyFunction($variable) == 3 ) {
statements;
}
// If the result of MyFunction() is anything other than true (note the !)...
if( !MyFunction() ) {
statements;
}
It is also possible to set explicit condition requirements by using an additional equals symbol. As you may know, the numerical value 1 is also treated as TRUE, and 0 as FALSE - however, if you only want the boolean value TRUE to be treated as TRUE and not the numerical value of 1, you can do so.
CODE
// In this if statement, the condition would be true.$variable = 1;
if( $variable == true ) {
statements;
}
// However, here, it would be false
if( $variable === true ) {
statements;
}
// Here it would be true, because the absolute value of $variable is not TRUE
if( $variable !== true ) {
statements;
}
In some situations, it is more practical to use a conditional operator than a full if statement. A conditional operator allows you to turn a long if statement into a single line of code, however, it reduces the ability of other programmers (or even yourself) to read the script, and sometimes isn't suitable. It is most useful for quickly assigning a conditional value to a variable, and works like this: condition ? true : false; where TRUE is the result of a true condition and false the opposite.
CODE
// An if statementif( $variable == 5 ) {
$variable = 3;
} else {
$variable = 8;
}
// Exactly the same statement in the form of a conditional operator
$variable = ($variable==5) ? 3 : 8;
As you can see, a conditional operator is much more compact than an if statement. More than one condition can be specified by using multiple conditional operators within each other. It can get a bit complex, but here is a quick example:
CODE
// If statementif( $variable1 == 5 && $variable2 == 1 ) {
$variable1 = 6;
} else {
$variable2 = 7;
}
// Conditional operator
$variable1 = ($variable1==5) ? ($variable2==1) ? 6 : 7 : 7;
As you can see (sort of), the two conditions are still there, as are the two possible results.
Switch()
The Switch() structure allows for you to take a different action depending on the value of something. Although not always the best option, it can sometimes replace the need for a series of if statements that evaluate the same value but require a different result. For example:
CODE
$variable = 23;// Here, $variable is checked to see if it equals 12, 18, 23, or something else.
if( $variable == 12 ) {
statement1;
} elseif( $variable == 18 ) {
statement2;
} elseif( $variable == 23 ) {
statement3;
} else {
statement4;
}
// Switch can replace all of the if and elseif statements
switch( $variable ) {
case 12:
statement;
break;
case 18:
statement2;
break;
case 23:
statement3;
break;
default:
statement4;
}
Keep in mind that the 'break' statement must be used after the final statement in each respective case to inform the script that it has met its condition and carried out the required statements. The 'default' case is what will occur if none of the other cases match, and doesn't have to be included. Any variable type can be used - string, boolean, numerical, whatever.
While() and For() loops
Loops are an easy way for a set of statements to be repeated until a requirement or condition is met. The conditions can be exactly the same as in If statments, so I won't re-cover all of that. Keep in mind that you can break out of a loop at any time by using the Break statement (which is the equivalent of the return statement in a function).
The While loop is probably the most basic and easy to use loop there is. The condition is evaluated only at the beginning of each loop (and every time the loop is repeated) - so if the condition is false at the start of the loop, but changes during the loop's cycle, it will continue until the next iteration unless additional checks are done.
CODE
// The while loop syntaxwhile( condition ) {
statement(s);
}
// Simple while loop which increments the value of $variable until it is greater than 25
$variable = 0;
while( $variable <= 25 ) {
$variable++;
}
The do...while loop is exactly the same as the while loop, however, the condition is evaluated only at the end of the loop. This means that at least one instance of the loop will occur, even if the condition is never true.
CODE
// The do...while loop syntaxdo {
statement(s);
} while ( condition );
// Same as the while loop shown above
$variable = 0;
do {
$variable++;
} while( $variable <= 25 );
// The value of $variable will still be incremented, even though the condition is true from the start.
$variable = 26;
do {
$variable++;
} while( $variable <= 25 );
Both while and do...while loops only run while the condition is true, but as I said, only check the condition once for each iteration.
The For loop is slightly more advanced than both the while and do...while loops, and is a bit more difficult to explain. The basic syntax is something along the lines of:
CODE
for( expression1; condition; expression2 ) {statements;
}
Now, let me try and explain what each of the three arguments mean. The first argument is an expression that is only executed the first time the loop is run. It doesn't matter how many times the loop repeats itself, the expression will never be repeated again in that instance of the For loop. It is most often used for assigning a value to a counter which is used again in the condition. The condition can, once again, be anything, and is checked at the beginning of every repetition of the loop. The final argument is a second expression which is executed on every iteration at the very end (similar to the do...while loop). The most common usage for the For loop is to execute a set of statements a certain number of times:
CODE
// This will loop 25 times. It works by assigning a value of 1 to the variable $i, then looping until it is equal to or greater than 25, incrementing it by one on each loop.for( $i=1;$i<25;$i++ ) {
statements;
}
This is useful for looping through arrays and string offsets and the like. Now, the tricky thing with the For loop is that any of the conditions can be 'nothing'. You could, if you wanted to, simply have for( ; ; ) and it would still work fine (however, the loop would repeat indefinately until explicitly stopped). This allows you to place your own set of condition evaluations within the For statement in whichever way you like, and you can use the Break statement to stop the looping at any time.
You can include any number of loops within any number of other loops, and different types of loops can exist within each other. Here is an example (you probably wouldn't do this, but it demonstrates what you can do if you need to):
CODE
// The for loop would be executed 100 times, which would on each loop execute the while loop 100 times, of which each iteration would execute the do...while loop 100 times.for( $i=0;$i<100;$i++ ) {
$a = 0;
while( $a<100 ) {
$a++;
$b = 0;
do{
$b++;
} while( $b<100 );
}
}
To be continued...
QUOTE (bluhapp)
do you actually wrote this? or you just copied it? if you just copied it.. better to quote it...Second, this is an awesome tutorial. It will be very helpful for beginners learning PHP, and while they're here, they can apply for an account and try it out. Thanks for posting it.
Another site that I found is: http://www.hudzilla.org/phpbook/read.php/22_0_0 (Practical PHP Programming)
But like I said the way it was presented is quite good and I'm hoping you'll write some more but this time with working examples
And thanks for that, snlildude87. bluhapp, whilst I'm not offended by your question, I like to think I am 'above' plagiarizing content and attempting to take the credit for it. All the same, feel free to use any search engine to check it if you wish.
I will write some more later (by which I mean, sometime in the next few years), and I will try and improve it according to your comments.
what's the difference between PHP and CGI?
As ive stated, i will attempt a well written continuance on Spectres great tutorial, unless Spectre refuses >.<
QUOTE (liauce)
Wow, seems very complicated. Is there a powerful software that let's you create PHP easily. Something easy to use.what's the difference between PHP and CGI?
CGI is a Perl (Im am not shure) or Python script. I think its perl!
Anyway, thanks for all your comments. Maybe I'll get around to writing up a second part some time. And HmmZ, feel free to expand on it.
A few notes:
1. Instead of using <? ?>, which is a shortcut (and may not work in some servers), use <?php ?>
2. Try to improve your indentation.
3. There are major differences between the comparision operator "==" (equal) and "===" (identical).
For example, "php" == 0 returns true, but "php" === 0 doesn't.
This is a really great tutorial but I think its Aimed more at the users who know the really basic stuff about PHP. I'm not really sure, but I think theres more basic stuff to PHP than what is already stated in this section of the guide.
Also, just really curious, but do you actually have to know HTML first to learn PHP?
QUOTE
PHP started as a Perl module. Now it may be installed independently; as a apache mod.That was a long time ago - when PHP first came about. It moved to an executable CGI after that, and is now available in various forms, including an Apache module (although it is in no way limited to this).
QUOTE
1. Instead of using <? ?>, which is a shortcut (and may not work in some servers), use <?php ?>I do always use <?php ?> in scripts. In the beginning of the tutorial, I noted that anything outside of the <? ?> tags will be ignored - but this isn't unique to PHP. There are numerous scripting engines (some more widely used than otehrs) that use <?(.*?) ?> to determine what should be processed and what shouldn't. It is true, however, that using <?php ?> is best practise and should always be compatible.
QUOTE
2. Try to improve your indentation.Normally, indentation is up to 9 blank spaces, whether they are actually 9 consecutive instances of 0x20 or a single 0x9 (incrementing each level - or least, that's how I do it); IPB trims the character 0x09, and I -think- it trims more than a few consecutive spaces or character 0x20. As such, code in this post is not particularly well indented. That aside, it is only concept code - most of the code posted here would not actually work anyway (or would have very little value) in the form in which it currently exists (eg. '} else { statement; }' - obviously, not a real statement). Structure is not incredibly important in this particular tutorial (and the only reason it matters elsewhere is for ease of readibility, something which, for one reason or another, is not always wanted).
QUOTE
3. There are major differences between the comparision operator "==" (equal) and "===" (identical).For example, "php" == 0 returns true, but "php" === 0 doesn't.
I already mentioned this in 'if...then..else'. There are not major differences - the former checks only the value, the latter both value and type (eg. $x == 4 would match a string value of '4'; $x === 4 would not). See: 'It is also possible to set explicit condition requirements by using an additional equals symbol...'. I didn't cover it in great detail, but it was mentioned.
Thanks a lot.
I will see If I learn something.
QUOTE
That was a long time ago - when PHP first came about. It moved to an executable CGI after that, and is now available in various forms, including an Apache module (although it is in no way limited to this).Yes, I was answering him: PHP started as a Perl module and now MAY be installed as an Apache module.
I didn't know IPB would mess the indentation
About the equal and identical operators, although they are apparently the same thing, they are very different. There was a security flaw in phpBB (security flaw number 6.57 x 10^6) that was fixed changing == to ===
QUOTE (Spectre)
I already mentioned this in 'if...then..else'. There are not major differences - the former checks only the value, the latter both value and type (eg. $x == 4 would match a string value of '4'; $x === 4 would not). See: 'It is also possible to set explicit condition requirements by using an additional equals symbol...'. I didn't cover it in great detail, but it was mentioned.I thought I was fairly good with PHP, by no means an expert but knew enough to get by. I learnt something from the tutorial, I wasn't aware of '===' until now. Thanks!
Excellent tutorial Spectre, you obviously spent a lot of time putting it together, well done! I hope you decide to complete the "To be continued..." section soon.
P.S. While it is true you cannot just preview a PHP script in action in your browser like you can HTML, you can set up your own personal web server with PHP running and test scripts that way. That's what I do, you just need to remember to change the server parameters (if any) in the script, such as connection parameters for a mysql database, when you finally upload to an online server.
QUOTE (Avalon)
P.S. While it is true you cannot just preview a PHP script in action in your browser like you can HTML, you can set up your own personal web server with PHP running and test scripts that way. That's what I do, you just need to remember to change the server parameters (if any) in the script, such as connection parameters for a mysql database, when you finally upload to an online server.Yes, use something like XAMPP
http://sourceforge.net/projects/xampp/
Another create a config file (which will be required every time).
For example:
define ("MYSQL_USER", "mendez");
and:
require 'config.php';
mysql_connect("localhost", MYSQL_USER, ...);
Easy...
thanks
acumentech
[note=wassie]please dont quote such long posts[/note]
Similar Topics:
Cartoonsmart.com Is Giving 8 Hours ...
Do You Recommend Any College Progra...
Is This Possible With Php ?
Dos 6.22 Trick With Ramdrive Make a legacy app not need a hard drive (0)
|
(19) Pet/animal Care Forum Online veterinary advise
|
Loading...
HOME 





Learn PHP Tutorial 1 - Basic Syntax
Learning the Basic's of PHP Programming - Tutorial 1
Learning PHP - 1 - Basics
PHP Basics: Serverside Programming Languages
PHP Basics: Installing phpBB
(Learn PHP) Basics Install a Webserver with PHP and MySQL Windows
PHP Basics - Learn how to display text
PHP Basics: Basic function
Learn PHP Basics in 17 Videos
PHP Basics: Advanced function

