Hello and welcome to the Webmasters Forums!. This is the best place to get webmasters resources for free. Get $2 for free today, read more - Make your payment today. Download premium and professional templates for free. Get free web hosting without ads, read more. You can get lot more by simply join with this forum. To gain full access to the forums you must sign up for a free account.


Post Reply  Post Thread 

Syntax

Post Bank
Posting Manager
******

Posts: 995
Group: Forum Team
Joined: Sep 2006
Status: Online
Make money from now. You can make money just for posting on this forum. Every discussions on this community gives you more money. $2 minimum payout. So get your payment today, SignIn with this forum.

Signin to Remove this Post

bomber
Junior Member
*


Posts: 34
Group: Registered
Joined: Sep 2006
Status: Offline
Reputation: 0
Points: 250 (Donate)
Post: #1

Cool Syntax


Where to put PHP code.

When the PHP program runs through your script, it looks for either <?php or <? then runs everything from there until the next ?>

You can configure PHP to run code between <% and %> tags too (ASP) though on IIS this probably isn't the wisest of ideas.

You need to tell your web server to run PHP files through the PHP program, too. This depends on which web server you have, though the PHP package has good instructions for most of the popular types. You should put your PHP code in files with the extension .php and configure your webserver to run .php files through the PHP program, though you can also force PHP to handle all .html files. The advantage to setting up .php as an extension is that files with no PHP code won't go through the PHP program, so you'll get better server performance.


Statements

All statements end with a ;

Whitespace is ignored, so you can stack several commands on one line, as long as you end every statement with a ;

Single line comments begin with // and finish at the end of the line

Multiple line comments begin with /* and end with */

You can group operations in brackets ( ) to make them more readable to humans. In fact it's highly recommended anyway so you know exactly what's going to happen when you run the code.


Variables

In PHP as in most computer programming languages, data can be stored in named areas of memory called variables. Variables can contain numbers, text, even binary data, as well as arrays (lists). They're also used to store references to files and database query results.

Arrays are special, so I'll go into those separately, but for the most part using variables is simple. All variable names begin with a $ and are followed by one or more letters. You can use numbers, too, and underscores ( _ ), but not spaces. Variable names are case sensitive - beware! $FOO is not the same as $foo.

$foo = 3;
$myline = "Hello world";

Unlike some other languages, you don't have to declare your variables before you use them, though for security reasons, it's recommended that you declare some of them (for example, session variables). I'll cover this in greater detail later.


Constants

Constants are much like variables, except you can't change them. You can declare them at the beginning of a script and use them instead of any fixed number that you can't be sure will never change. PHP sets some constants for you, like TRUE, FALSE and NULL.

To create a constant, you use the define() function. Constants can be named just like variables, and they can store anything a variable can except an array.

define("MY_CONSTANT", "Hello World");
echo MY_CONSTANT; // prints "Hello World"

A lot of mathematical constants are also preset for you when PHP starts up, namely M_PI for pi. Read the "Mathematical functions" section of the PHP manual for the complete list.


Strings

Strings are text, pure and simple. There's two ways of storing strings, inside single quotes and double-quotes. Using "double-quotes" allows you to use special characters like \n for a newline. The backslash character marks the next character as special, though the only characters you can backslash in 'single-quoted' strings are \' (a single quote) and \\ (a backslash).

Some other special characters (for double-quoted strings)

\t


TAB

\n


newline

\r


carriage-return. In DOS text-files, a new line is \r\n, though in practice in Windows you can get away with UNIX format, which is just \n

\$


$

\'


'

\"


"

The most important difference between single and double-quoted strings is that double-quoted strings can contain variable names:

$foo = 'This doesn\'t work'; // Oh yes it does!
$foo = "Matt's second line also works";

$age = 18;
echo 'Bob is $age'; // prints "Bob is $age"
echo "Bob is $age"; // prints "Bob is 18"

Check out the manual for more string stuff -- this is generally enough to get along with in daily use.


Operators

There are some operators that work directly on variables to save you time and effort in programming. For example, ++ and -- work to add and remove 1 from contents of the variable given:

$foo = 3;
$foo = $foo + 1 // The 'old' way of doing this.
$foo++; // $foo is now 5
++$foo; // $foo is now 6

The difference between ++$foo and $foo++ is the point at which the number is added. If you're using $foo in a statement more complicated than those above, you'll find that :

$foo = 3;
$bob = $foo++; // $bob is 3, $foo is 4.
$foo = ++$bob; // $bob and $foo are both 4

In the first line, we set $foo to 3. The following line reads in plain English as "Set $bob to the value of $foo, then add one to $foo", whereas the last line reads "Add one to $bob and set $foo to the new value". In general, if you have to think about what's going to happen, then you should write your code in a more simple way -- think of the poor git who's going to replace you! You're excused if:

*

you're not coding for money
*

you won't be replaced
*

you remember why you do everything that you do and never have to check your own notes.

If you want to add/subtract more than one, use the += and -= operators. For strings you can use the .= operator.

$foo = "Fred is ";
$foo .= " Bob's friend"; // $foo now contains "Fred is Bob's friend";

$foo = 1;
$bob = 3;

$foo += 2; // $foo is now 3
$foo += $bob; // $foo is now 6

The usual operators

Use + to add, - to subtract, / to divide, * to multiply, and % to get the modulus (remainder). These make sense with numbers. They don't with words. Use . to join multiple items (like pieces of text):

echo "You have " . $items . " items.";

Comparison operators

Use comparison operators in tests like if, while and for loops to test a condition. These operators will compare the items on either side and will return true or false. Again, most of these only work meaningfully with numbers.

$a == $b Returns true if the contents of $a match those of $b, false otherwise.
$a < $b True if $a is less than $b
$a > $b True if $a is greater than $b
$a <= $b True if $a is less than, or equal to $b
$a >= $b True if $a is greater than, or equal to $b

Logical operators

As above, these operators will return true or false depending on the outcome of the test it performs on the two sides of the operator. It takes each side to be a binary value, either true or false. In PHP, 0 and NULL are false, everything else (including negative numbers) is TRUE.

&&


AND


Returns true if both sides of the operator evaluate to true. However, if the left hand side isn't TRUE, PHP won't bother testing the right hand side.

&!


AND NOT


Returns true if the left side is TRUE and right side is FALSE.

||


OR


Returns true if the left side or the right side is true. Note that PHP won't bother checking the right hand side if the left hand side is true.

!


NOT


This is one-sided only. ! $a will be TRUE if $a is FALSE.

Because PHP (Like C and Perl) "short-circuits" these operators when it can, you can use them as control structures:

($fp = fopen("filename.txt", 'r')) || die("Couldn't
open file for read");

PHP runs the first side, ($fp = fopen("filename.txt", 'r')). If the fopen() function call opens the file and the file pointer is stored in $fp, then this side of the line returns TRUE. || means "one side or the other (or both) must be true", PHP doesn't bother running the right hand side because it knows that one side is already true which is what the operator requires. Now, if the file-open function had failed, the left hand side would've returned FALSE so PHP would -=have=- to check the right hand side to see if that's true. The right hand side runs the die() function which quits PHP with an error message, in this case "Couldn't open file for read". In short, PHP quits if it can't open the file.


Type casting

Like Perl, variables are cast automatically into the right types (integer, floating point, string, etc.) though you can force them if you want. Just put the required type in front of the variable in brackets

$mynum = 3.01;
$intnum = (int) $mynum;

Check this out in the PHP manual if you want to know more about typecasting. In general it's not necessary since there are functions for dealing with (for example) number formatting.


Arrays

Arrays in PHP are pretty much different from any other implementation the author has seen in other languages. The concept of an array is simple - it's a list of items:

$my_array = array( "bob", "fred", "barney", "thelma" );

Accessing the array is done as a whole ($my_array) or by array item. Items are numbered from 0 at the beginning, so $my_array[0] is "bob" and $my_array[3] is "thelma"

So far, this should be familiar to many coders. You don't have to declare arrays in PHP, or their length - the size of an array will adapt to meet the contents. Array items can be strings, numbers, even other arrays:

$my_array[4] = array("billy-anne", "billy-bob", "billy-sue");

A useful function to learn here is the print_r() function to show the structure and contents of any variable. You can use it to help you visualise how this data is arranged. You can also run PHP from the command-line if you have the php-cli program in your PHP installation package (from version 4.2.x onward). To run a script from the command line, use:

php-cli file.php

The stops the HTTP headers from showing on the command-line, which keeps your screen tidy.

Try saving the following lines to a file then running it through PHP.

<?
$my_array = array( "bob", "fred", "barney", "thelma" );
$my_array[4] = array("billy-anne", "billy-bob", "billy-sue");

print_r($my_array);

>

Now, the powerful and unique feature of PHP arrays (and also a big stumbling block for many) is that PHP arrays aren't just numbered, they're named. For good coding, you shouldn't assume that your arrays are numbered, or even numbered in order! This means that a traditional for( $i = 0; $i < count($my_array); $i++) loop won't necessarily work.

Named arrays are assigned slightly differently, but not much - you can use this format for numbered arrays too:

$this_user = array( "firstname" => "Bob",
"surname" => "Smith",
"age" => 24 );
$this_user['firstname'] = "Robert";

Hopefully you can see from this example why named arrays are useful. Later on in the database section we show how you can retrieve rows from a database query and store each row as a named array. Identifying in your HTML code what $row[4] is can be annoying and time-consuming, because you have to go back and find the SQL statement and count to the 5th field... etc. But if you see $row["age"] you know exactly what part of the data is being shown.

(Un)fortunately it doesn't end there with arrays - you can treat them like a stack and push things onto, or pop them off of the top, like some programmers would with assembler or forth. PHP also lets you shift and unshift items to/from the bottom of the stack too. And because you can store arrays in arrays, you can simulate trees. If you're not a full programmer yet and this means nothing to you.. good! Less work for me :-)

Read the manual's function reference - it has a whole section of array functions that let you shuffle, reverse, sort, splice, count, merge, and filter arrays. You can subtract one array from another, or build an array of the unique values of another array.. in short, you can do a helluva lot with arrays. They're one of the most powerful features of PHP.

I'll cover some simple array functions (like looping over the contents) and ask you to play with the manual a little.

18-09-2006 11:22 PM
Find all posts by this user Quote this message in a reply
clookid
Advanced Member
***


Posts: 184
Group: Registered
Joined: Oct 2006
Status: Offline
Reputation: 4
Points: 134 (Donate)
Post: #2

RE: Syntax


Bomber, I am going to publish these tutorials around a little. I will mention they are not written by me but by you, please send me an email to clookid@gmail.com if you would like me to remove them.


Veebra Articles - Computer and technology related articles.
11-01-2007 09:02 AM
Find all posts by this user Quote this message in a reply
Cedik
Moderator
*****


Posts: 424
Group: Moderators
Joined: Aug 2007
Status: Away
Reputation: 2
Points: 575 (Donate)
Post: #3

RE: Syntax


Thanks for this tutorial! It made me realise why I made some mistakes once.
It's very usefull for someone who makes it's first steps in programming as it is for someone who knows programming but wants to start learning php too. Combined with what I allready knew, now I can look trough the php files with different eyes. If only I knew these information before... but better later than never!


MyBB.ro|Extra.animezup.com|Picture with me ^^|Animezup.com|Forum.animezup.com|Manga-anime.ro|My blog^^
02-08-2007 06:50 AM
Visit this user's website Find all posts by this user Quote this message in a reply
ivenms
Administrator
*******


Posts: 2,179
Group: Administrators
Joined: Sep 2006
Status: Offline
Reputation: 14
Points: 4389 (Donate)
Post: #4

RE: Syntax


Yes...

This is one of the best tutorials we here have. This tutorial includes all basics of PHP Syntax.

To know more advanced coding of PHP, Visit: http://php.net


Read: General Rules & Policies before posting.
Make Money By Posting | Earning and Exchanging Points | Add Your Links
02-08-2007 05:25 PM
Find all posts by this user Quote this message in a reply
walsh
Senior Member
****


Posts: 401
Group: Registered
Joined: Oct 2006
Status: Offline
Reputation: 0
Points: 680 (Donate)
Post: #5

RE: Syntax


Thanks for the tutorial. That is really a good abstract about the language PHP on a single page.

It help me to learn PHP.


09-08-2007 07:21 AM
Find all posts by this user Quote this message in a reply
Post Reply  Post Thread 

View a Printable Version
Send this Thread to a Friend
Subscribe to this Thread | Add Thread to Favorites
Rate This Thread:

Forum Jump:

Sign In to Remove Ads

Download 1000's of web templates. Unlimited access!
World's Best Web Hosting
Website of the Month

Create-a-Page for Free
SOTM June 2008


Accepting Submissions
for July 2008
Resources

Recommended Sites:



Visit our Sponsors!

Current time: 07-09-2008, 06:32 AM


Copyright © 2002-2008 MyBB Group
Powered By MyBB