Jump to content
xisto Community

Php - The Basics Learn the basics of PHP

Recommended Posts

I should point out that I originally put this tutorial together for another site, but decided against it and to place it here instead (because I love you guys... ~sniffle, wipe a tear away~).


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


// Standard function definition with no argumentsfunction MyFunction() {}// Function definition with a single required argumentfunction MyFunction( $argument ) {  echo $argument;}// Function definition with multiple required argumentsfunction MyFunction( $argument1, $argument2, $argument3 ) {  echo "$argument1, $argument2, $argument3";}// Function definition with single optional argumentfunction 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.


// Returns nothing - simply exits the function.function MyFunction() {  return;}// Returns the boolean value TRUEfunction MyFunction() {  return true;}// Returns a substring of the argumentfunction MyFunction( $argument ) {  return substr($argument,0,3);}



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:


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


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


// 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 Elseif( condition ) {  echo 'True';} else { echo 'False';}// Using ElseIfif( $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.


// Requires that all conditions are trueif( $variable1 == 123 && $variable2 == 'xyz' ) {  statements;}// Requires that either condition be trueif( $variable1 == 123 || $variable2 == 'xyz' ) {  statements;}// Any number of conditions can existif( 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:


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


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


// In this if statement, the condition would be true.$variable = 1;if( $variable == true ) {  statements;}// However, here, it would be falseif( $variable === true ) {  statements;}// Here it would be true, because the absolute value of $variable is not TRUEif( $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.


// 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:


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




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:


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


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


// 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:


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:


// 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):


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

Share this post

Link to post
Share on other sites

do you actually wrote this? or you just copied it? if you just copied it.. better to quote it...


First of all,this is Spectre we're talking about. He used to be an admin and a moderator, but got "kicked" off because he was not active. I don't even have to google this, and I know that he typed this. Please don't make accusations like this again without researching first.


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.hackingwithphp.com/22/0/0 (Practical PHP Programming)

Share this post

Link to post
Share on other sites

I like how the tutorial being presented. But for me it lacks something, an important thing actualy. Since the tuorials are basicaly the basics of syntax, I mean conditional statements, data types.... anyway, what it lacks is an example of a working php page. The point I'm getting to is, after reading the tutorials a beginner can not use what he learned becuase basicaly it was just all about syntax. Although it mentions the opening and closing tag but thats it. I hope you get my point, im not good in english :PBut 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 :(

Share this post

Link to post
Share on other sites

i like the guide but i still dont understand it. i dont no why but sites dont give like for the if statement part thatas easy to understand but some of the other stuff not easy to understand(may just be from me not understanding not everyone) if there is a easy guide to understand can someone pm the link but besides this i like the guide

Share this post

Link to post
Share on other sites

I'm guessing everything that hasnt been already explained will be explained in another tutorial, hence the "to be continued..."

Share this post

Link to post
Share on other sites

Thanks for the feedback. I've written it how I think I would have found easy to understand when I was first starting out with PHP. It obviously isn't going to suit every single other person - but then again, nothing ever does. Hopefully there will be those who will learn a little something from it.


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.

Share this post

Link to post
Share on other sites

again not bad, now only if i could actually remember coding and do it by scratch myself instead of copy and pasting every thing :P. but this should help those wanted to get a good idea on how it works out, good job Spectre.

Share this post

Link to post
Share on other sites

If i have some time today, i will attempt to provide an example page using the tutorial Spectre has written, very nicely written tutorial spectre, but yes, a newbie does need an example. From my own experience, i know that many people dont like theory (including myself) and therefore need examples and assignments, practise practise practise, is the keyword :ph34r:As ive stated, i will attempt a well written continuance on Spectres great tutorial, unless Spectre refuses >.<

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.