Loading...


bookmark - Php - The Basics Learn the basics of PHP

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.
bookmark - Php - The Basics Learn the basics of PHP  
Quickly Post to Php - The Basics Learn the basics of PHP w/o signup Share Info about Php - The Basics Learn the basics of PHP using Facebook, Twitter etc. email your friend about Php - The Basics Learn the basics of PHP Print
Reply / Comment New Discussion / Topic Share / Bookmark E-Mail a Friend Print


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

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 arguments
function 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 statement
if( 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 statement
if( 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 true
if( $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 statement
if( $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 statement
if( $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 syntax
while( 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 syntax
do {
 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...

   Mon Sep 12, 2005    Reply         

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

   Mon Sep 12, 2005    Reply         

QUOTE (bluhapp)

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.hudzilla.org/phpbook/read.php/22_0_0 (Practical PHP Programming)

   Mon Sep 12, 2005    Reply         


:P i gonna have to take my time and actually read :(

   Mon Sep 12, 2005    Reply         

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

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

   Mon Sep 12, 2005    Reply         

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

   Mon Sep 12, 2005    Reply         


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

   Mon Sep 12, 2005    Reply         

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.

   Mon Sep 12, 2005    Reply         

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.

   Mon Sep 12, 2005    Reply         

yea thanks dfor making the guide i guess i could just keep re reading it

   Mon Sep 12, 2005    Reply         

sorry... no offence in your post. good article...

   Tue Sep 13, 2005    Reply         

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?

   Mon Sep 26, 2005    Reply         

wow i ve been wondering what php as based and this tut helped me alot.

   Mon Sep 26, 2005    Reply         

Man thanks ALOT this is helping me ALOT...I bought a book and i didnt look at it and it asumes you know os basic PHP...I know there are alot of websites with tutorials, but i love my Trap17 and this thread thanks man :ph34r:

   Mon Sep 26, 2005    Reply         

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

   Thu Sep 29, 2005    Reply         

Nice tutorial! :huh:

   Fri Sep 30, 2005    Reply         

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!

   Fri Sep 30, 2005    Reply         

This is getting slightly off topic. But anyway, Perl is a CGI; so is Python. PHP can be run as a CGI, but most people usually favor the module (for security and other reasons - but not all web servers support this). CGI stands for common gateway interface, and is basically a server-side program that the web server can interface with, allowing for certain scripts to be executed on the server.

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.

   Sun Oct 2, 2005    Reply         

PHP started as a Perl module. Now it may be installed independently; as a apache mod.

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.

   Tue Oct 4, 2005    Reply         

thx for the tut, im just starting out so it was very helpful. however, is there a way to make is easier? like some sort of php software? there are like html software and html editing, so there may be a php thinga miggy

   Tue Oct 4, 2005    Reply         

Wow, this is really complicated stuff.
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?

   Wed Oct 5, 2005    Reply         

mendezgarcia, I'll assume that was directed at me.

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.

   Wed Oct 5, 2005    Reply         

Just to answer to those of you who are looking for "php visual programs". There is NO such a thing. PHP is programming language and you can see its results only after execution (somtimes compilation). Anyway, to learn PHP you must learn the language itself, you cant "draw" it or anything like that, just simple coding. And you dont have to know HTML to write PHP code, but it's highly recommended, so you can implement what you create with PHP into the real world project.

   Wed Oct 5, 2005    Reply         

Wow, I found this tutorial amazing for a beginer like me. I just have bookmarked it because I think it will help me in the future. Iīm trying to learn php and although I donīt have too much free time I hope to get it finally. Maybe some day I could make my own scripts without disturbing my friends constantly with code issues. :huh:

Thanks a lot.

   Wed Oct 5, 2005    Reply         

Nice tutorial, I will take my time to read it. A lot of text....
I will see If I learn something.

   Thu Oct 6, 2005    Reply         

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

   Wed Oct 12, 2005    Reply         

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.

   Wed Oct 12, 2005    Reply         

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

   Fri Oct 14, 2005    Reply         

really nice attempt and should be praised. You should also mention some thing about sessions and cookies.

thanks

acumentech

[note=wassie]please dont quote such long posts[/note]

   Tue Oct 18, 2005    Reply         

This guide is pretty good for me. Actually it has helped me a lot to start in PHP Thanks Spectre .

   Thu Oct 20, 2005    Reply         

Quickly Post to Php - The Basics Learn the basics of PHP w/o signup Share Info about Php - The Basics Learn the basics of PHP using Facebook, Twitter etc. email your friend about Php - The Basics Learn the basics of PHP Print
Reply / Comment New Discussion / Topic Share / Bookmark E-Mail a Friend Print


Similar Topics:

Cartoonsmart.com Is Giving 8 Hours ...

Freebies Title: Cartoonsmart.com is giving 8 hours of free flash mx lessons Freebies Description: CartoonSmart is very popular, for google.com (Page rank: 5), and for flash geeks, developers and addicted to flash technology, like myself i should say, and this lessons are so good that yo ...more

   11-Apr-2009    Reply         

Do You Recommend Any College Progra...

Do you recommend any college programs for php learning? I want to learn php, i live in canada, any ideas? ...more

   26-Jul-2009    Reply         

Is This Possible With Php ?

Dear friends, recently i came across the basics of Php and i was thrilled by such wonderful Server-side HTML embedded scripting language. I guess for building a good dynamic website php rocks. Here i have a major query , and hope some one can help me out. In Php is the following method ...more

   21-Aug-2009    Reply         

Dos 6.22 Trick With Ramdrive Make a legacy app not need a hard drive   Dos 6.22 Trick With Ramdrive Make a legacy app not need a hard drive (0) (19) Pet/animal Care Forum Online veterinary advise  Pet/animal Care Forum Online veterinary advise