Tuesday, January 29, 2008

PHP Basic syntax

Escaping from HTML

When PHP parses a file, it looks for opening and closing tags, which tell PHP to start and stop interpreting the code between them. Parsing in this manner allows php to be embedded in all sorts of different documents, as everything outside of a pair of opening and closing tags is ignored by the PHP parser. Most of the time you will see php embedded in HTML documents, as in this example.

<p>This is going to be ignored.</p>

<?php echo 'While this is going to be parsed.'; ?>

<p>This will also be ignored.</p>

You can also use more advanced structures:

Example#1 Advanced escaping

 

<?php

if ($expression) {

?>

<strong>This is true.</strong>

<?php

} else {

?>

<strong>This is false.</strong>

<?php

}

?>

This works as expected, because when PHP hits the ?> closing tags, it simply starts outputting whatever it finds (except for an immediately following newline - see instruction separation ) until it hits another opening tag. The example given here is contrived, of course, but for outputting large blocks of text, dropping out of PHP parsing mode is generally more efficient than sending all of the text through echo() or print().

There are four different pairs of opening and closing tags which can be used in php. Two of those, <?php ?> and <script language="php"> </script>, are always available. The other two are short tags and ASP style tags, and can be turned on and off from the php.ini configuration file. As such, while some people find short tags and ASP style tags convenient, they are less portable, and generally not recommended.

Note: Also note that if you are embedding PHP within XML or XHTML you will need to use the <?php ?> tags to remain compliant with standards.

Example#2 PHP Opening and Closing Tags

 

1. <?php echo 'if you want to serve XHTML or XML documents, do like this'; ?>

2. <script language="php">

echo 'some editors (like FrontPage) don\'t

like processing instructions';

</script>

3. <? echo 'this is the simplest, an SGML processing instruction'; ?>

<?= expression ?> This is a shortcut for "<? echo expression ?>"

4. <% echo 'You may optionally use ASP-style tags'; %>

<%= $variable; # This is a shortcut for "<% echo . . ." %>

While the tags seen in examples one and two are both always available, example one is the most commonly used, and recommended, of the two.

Short tags (example three) are only available when they are enabled via the short_open_tag php.ini configuration file directive, or if php was configured with the --enable-short-tags option.

Note: If you are using PHP 3 you may also enable short tags via the short_tags() function. This is only available in PHP 3!

ASP style tags (example four) are only available when they are enabled via the asp_tags php.ini configuration file directive.

Note: Support for ASP tags was added in 3.0.4.

Note: Using short tags should be avoided when developing applications or libraries that are meant for redistribution, or deployment on PHP servers which are not under your control, because short tags may not be supported on the target server. For portable, redistributable code, be sure not to use short tags.

Monday, January 28, 2008

Control Structures in PHP: WHILE

while loops are the simplest type of loop in PHP. They behave just like their C counterparts. The basic form of a while statement is:

   

while (expr)

statement

The meaning of a while statement is simple. It tells PHP to execute the nested statement(s) repeatedly, as long as the while expression evaluates to TRUE. The value of the expression is checked each time at the beginning of the loop, so even if this value changes during the execution of the nested statement(s), execution will not stop until the end of the iteration (each time PHP runs the statements in the loop is one iteration). Sometimes, if the while expression evaluates to FALSE from the very beginning, the nested statement(s) won't even be run once.

Like with the if statement, you can group multiple statements within the same while loop by surrounding a group of statements with curly braces, or by using the alternate syntax:

    

while (expr):

statement

...

endwhile;

The following examples are identical, and both print the numbers 1 through 10:


 

/* example 1 */

$i = 1;

while ($i <= 10) {

echo $i++; /* the printed value would be

$i before the increment

(post-increment) */

}


/* example 2 */

$i = 1;

while ($i <= 10):

echo $i;

$i++;

endwhile;

?>

Friday, January 25, 2008

Control Structures in PHP: IF

The if construct is one of the most important features of many languages, PHP included. It allows for conditional execution of code fragments. PHP features an if structure that is similar to that of C:

if (expr)

statement

As described in the section about expressions, expression is evaluated to its Boolean value. If expression evaluates to TRUE, PHP will execute statement, and if it evaluates to FALSE - it'll ignore it. More information about what values evaluate to FALSE can be found in the 'Converting to boolean' section.

The following example would display a is bigger than b if $a is bigger than $b:

  

<?php

if ($a > $b)

echo "a is bigger than b";

?>

Often you'd want to have more than one statement to be executed conditionally. Of course, there's no need to wrap each statement with an if clause. Instead, you can group several statements into a statement group. For example, this code would display a is bigger than b if $a is bigger than $b, and would then assign the value of $a into $b:

   

<?php

if ($a > $b) {

echo "a is bigger than b";

$b = $a;

}

?>

If statements can be nested indefinitely within other if statements, which provides you with complete flexibility for conditional execution of the various parts of your program.

Thursday, January 24, 2008

Control Structures in PHP: FOR

for loops are the most complex loops in PHP. They behave like their C counterparts. The syntax of a for loop is:
 

for (expr1; expr2; expr3)

statement

The first expression (expr1) is evaluated (executed) once unconditionally at the beginning of the loop.

In the beginning of each iteration, expr2 is evaluated. If it evaluates to TRUE, the loop continues and the nested statement(s) are executed. If it evaluates to FALSE, the execution of the loop ends.

At the end of each iteration, expr3 is evaluated (executed).

Each of the expressions can be empty or contain multiple expressions separated by commas. In expr2, all expressions separated by a comma are evaluated but the result is taken from the last part. expr2 being empty means the loop should be run indefinitely (PHP implicitly considers it as TRUE, like C). This may not be as useless as you might think, since often you'd want to end the loop using a conditional break statement instead of using the for truth expression.

Consider the following examples. All of them display the numbers 1 through 10:

 

<?php

/* example 1 */

for ($i = 1; $i <= 10; $i++) {

echo $i;

}

/* example 2 */

for ($i = 1; ; $i++) {

if ($i > 10) {

break;

}

echo $i;

}


/* example 3 */

$i = 1;

for (; ; ) {

if ($i > 10) {

break;

}

echo $i;

$i++;

}

/* example 4 */

for ($i = 1, $j = 0; $i <= 10; $j += $i, print $i, $i++);

?>

Of course, the first example appears to be the nicest one (or perhaps the fourth), but you may find that being able to use empty expressions in for loops comes in handy in many occasions.

PHP also supports the alternate "colon syntax" for for loops.

 

for (expr1; expr2; expr3):

statement

...

endfor;

Control Structures in PHP: ELSEIF

elseif, as its name suggests, is a combination of if and else. Like else, it extends an if statement to execute a different statement in case the original if expression evaluates to FALSE. However, unlike else, it will execute that alternative expression only if the elseif conditional expression evaluates to TRUE. For example, the following code would display a is bigger than b, a equal to b or a is smaller than b:
  

<?php

if ($a > $b) {

echo "a is bigger than b";

} elseif ($a == $b) {

echo "a is equal to b";

} else {

echo "a is smaller than b";

}

?>

There may be several elseifs within the same if statement. The first elseif expression (if any) that evaluates to TRUE would be executed. In PHP, you can also write 'else if' (in two words) and the behavior would be identical to the one of 'elseif' (in a single word). The syntactic meaning is slightly different (if you're familiar with C, this is the same behavior) but the bottom line is that both would result in exactly the same behavior.

The elseif statement is only executed if the preceding if expression and any preceding elseif expressions evaluated to FALSE, and the current elseif expression evaluated to TRUE.

Control Structures in PHP: ELSE

Often you'd want to execute a statement if a certain condition is met, and a different statement if the condition is not met. This is what else is for. else extends an if statement to execute a statement in case the expression in the if statement evaluates to FALSE. For example, the following code would display a is bigger than b if $a is bigger than $b, and a is NOT bigger than b otherwise:

<?php

if ($a > $b) {

echo "a is bigger than b";

} else {

echo "a is NOT bigger than b";

}

?>

The else statement is only executed if the if expression evaluated to FALSE, and if there were any elseif expressions - only if they evaluated to FALSE as well (see elseif).

Tuesday, January 22, 2008

Control Structures in PHP: DO-WHILE

do-while loops are very similar to while loops, except the truth expression is checked at the end of each iteration instead of in the beginning. The main difference from regular while loops is that the first iteration of a do-while loop is guaranteed to run (the truth expression is only checked at the end of the iteration), whereas it's may not necessarily run with a regular while loop (the truth expression is checked at the beginning of each iteration, if it evaluates to FALSE right from the beginning, the loop execution would end immediately).

There is just one syntax for do-while loops:

<?php

$i = 0;

do {

echo $i;

} while ($i > 0);

?>

The above loop would run one time exactly, since after the first iteration, when truth expression is checked, it evaluates to FALSE ($i is not bigger than 0) and the loop execution ends.

Advanced C users may be familiar with a different usage of the do-while loop, to allow stopping execution in the middle of code blocks, by encapsulating them with do-while (0), and using the break statement. The following code fragment demonstrates this:

<?php

do {

if ($i < 5) {

echo "i is not big enough";

break;

}

$i *= $factor;

if ($i < $minimum_limit) {

break;

}

echo "i is ok";

/* process i */

} while (0);

?>


Don't worry if you don't understand this right away or at all. You can code scripts and even powerful scripts without using this 'feature'.