Wednesday, February 27, 2013

Control Structures

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

The following example would display a is bigger than b if $a is bigger than $b:
<?phpif ($a $b)
    echo 
"a is bigger than b";?>

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:
<?phpif ($a $b) {
    echo 
"a is bigger than b";
} else {
    echo 
"a is NOT bigger than b";
}
?>

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:
<?phpif ($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.

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 numbers from 1 to 10:
<?php/* 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;
?>

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:
<?phpdo {
    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);?>

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. 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 numbers from 1 to 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$i <= 10; print $i$i++);?>

Monday, January 28, 2013

Variables

Basics

Variables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case-sensitive.
Variable names follow the same rules as other labels in PHP. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*' 



<?php
$var 
'Bob';$Var 'Joe';
echo 
"$var, $Var";     

 // outputs "Bob, Joe"$4site 'not yet';    
 // invalid; starts with a number$_4site 'not yet';    
 // valid; starts with an underscore$täyte 'mansikka';  
  // valid; 'ä' is (Extended) ASCII 228.?>



Predefined variables

PHP provides a large number of predefined variables to any script which it runs. 

PHP Superglobals
$GLOBALS
Contains a reference to every variable which is currently available within the global scope of the script. The keys of this array are the names of the global variables. $GLOBALS has existed since PHP 3.
$_SERVER
Variables set by the web server or otherwise directly related to the execution environment of the current script. Analogous to the old $HTTP_SERVER_VARS array (which is still available, but deprecated).
$_GET
Variables provided to the script via URL query string. Analogous to the old $HTTP_GET_VARS array (which is still available, but deprecated).
$_POST
Variables provided to the script via HTTP POST. Analogous to the old $HTTP_POST_VARS array (which is still available, but deprecated).
$_COOKIE
Variables provided to the script via HTTP cookies. Analogous to the old $HTTP_COOKIE_VARS array (which is still available, but deprecated).
$_FILES
Variables provided to the script via HTTP post file uploads. Analogous to the old $HTTP_POST_FILES array (which is still available, but deprecated). See POST method uploads for more information.
$_ENV
Variables provided to the script via the environment. Analogous to the old $HTTP_ENV_VARS array (which is still available, but deprecated).
$_REQUEST
Variables provided to the script via the GET, POST, and COOKIE input mechanisms, and which therefore cannot be trusted. The presence and order of variable inclusion in this array is defined according to the PHP variables_order configuration directive. This array has no direct analogue in versions of PHP prior to 4.1.0. See also import_request_variables().

Tuesday, January 22, 2013

Objects

Objects

Object Initialization

To initialize an object, you use the new statement to instantiate the object to a variable.
<?phpclass foo{
    function 
do_foo()
    {
        echo 
"Doing foo.";
    }
}
$bar = new foo;$bar->do_foo();?>

Converting to object

If an object is converted to an object, it is not modified. If a value of any other
 type is converted to an object, a new instance of the stdClass built in class is 
created. If the value was NULL, the new instance will be empty. 
Array converts to an object with properties named by array keys
 and with corresponding values. For any other value, a member
 variable named scalar will contain the value.
<?php
$obj 
= (object) 'ciao';
echo 
$obj->scalar;  // outputs 'ciao'?>

Array

Array
An array is a data structure that stores one or more values in a single value. For experienced programmers it is important to note that PHP's arrays are actually maps (each key is mapped to a value). 

PHP - A Numerically Indexed Array
If this is your first time seeing an array, then you may not quite understand the concept of an array. Imagine that you own a business and you want to store the names of all your employees in a PHP variable. How would you go about this?
It wouldn't make much sense to have to store each name in its own variable. Instead, it would be nice to store all the employee names inside of a single variable. This can be done, and we show you how below.

PHP Code:
$employee_array[0] = "Bob";
$employee_array[1] = "Sally";
$employee_array[2] = "Charlie";
$employee_array[3] = "Clare";
In the above example we made use of the key / value structure of an array. The keys were the numbers we specified in the array and the values were the names of the employees. Each key of an array represents a value that we can manipulate and reference. The general form for setting the key of an array equal to a value is:
  • $array[key] = value;
If we wanted to reference the values that we stored into our array, the following PHP code would get the job done.
Note: As you may have noticed from the above code example, an array's keys start from 0 and not 1. This is a very common problem for many new programmers who are used to counting from 1 and lead to "off by 1" errors. This is just something that will take experience before you are fully comfortable with it.

PHP Code:
echo "Two of my employees are "
. $employee_array[0] . " & " . $employee_array[1];
echo "<br />Two more employees of mine are "
. $employee_array[2] . " & " . $employee_array[3];

Display:
Two of my employees are Bob & Sally
Two more employees of mine are Charlie & Clare
PHP arrays are quite useful when used in conjunction with loops, which we will talk about in a later lesson. Above we showed an example of an array that made use of integers for the keys (a numerically indexed array). However, you can also specify a string as the key, which is referred to as an associative array.

PHP - Associative Arrays
In an associative array a key is associated with a value. If you wanted to store the salaries of your employees in an array, a numerically indexed array would not be the best choice. Instead, we could use the employees names as the keys in our associative array, and the value would be their respective salary.

PHP Code:
$salaries["Bob"] = 2000;
$salaries["Sally"] = 4000;
$salaries["Charlie"] = 600;
$salaries["Clare"] = 0;

echo "Bob is being paid - $" . $salaries["Bob"] . "<br />";
echo "Sally is being paid - $" . $salaries["Sally"] . "<br />";
echo "Charlie is being paid - $" . $salaries["Charlie"] . "<br />";
echo "Clare is being paid - $" . $salaries["Clare"];

Display:
Bob is being paid - $2000
Sally is being paid - $4000
Charlie is being paid - $600
Clare is being paid - $0


Strings

Strings

A string is series of characters. In PHP, a character is the same as a byte, that is, there are exactly 256 different characters possible. This also implies that PHP has no native support of Unicode. See utf8_encode() and utf8_decode() for some Unicode support.

 

Syntax

A string literal can be specified in three different ways.
  • single quoted
  • double quoted
  • heredoc syntax

Single quoted

The easiest way to specify a simple string is to enclose it in single quotes (the character ').
To specify a literal single quote, you will need to escape it with a backslash (\), like in many other languages. If a backslash needs to occur before a single quote or at the end of the string, you need to double it. Note that if you try to escape any other character, the backslash will also be printed! So usually there is no need to escape the backslash itself.

 



<?phpecho 'this is a simple string';

echo 
'You can also have embedded newlines in
strings this way as it is
okay to do'
;

 // Outputs: Arnold once said: "I'll be back"
 echo 'Arnold once said: "I\'ll be back"'; 
// Outputs: You deleted C:\*.*? 
echo 'You deleted C:\\*.*?'; 
// Outputs: You deleted C:\*.*?
 echo 'You deleted C:\*.*?'; 
// Outputs: This will not expand: \n a newline 
echo 'This will not expand: \n a newline'; 
// Outputs: Variables do not $expand $either 
echo 'Variables do not $expand $either';?>

Double quoted

If the string is enclosed in double-quotes ("), PHP understands more escape sequences for special characters:

Heredoc

Another way to delimit strings is by using heredoc syntax ("<<<"). One should provide an identifier after <<<, then the string, and then the same identifier to close the quotation.
The closing identifier must begin in the first column of the line. Also, the identifier used must follow the same naming rules as any other label in PHP: it must contain only alphanumeric characters and underscores, and must start with a non-digit character or underscore.

 

Floating point numbers

Floating point numbers

Floating point numbers (AKA "floats", "doubles" or "real numbers") can be specified using any of the following syntaxes:
<?php
$a 
1.234$b 1.2e3$c 7E-10;?>
Formally:
LNUM          [0-9]+
DNUM          ([0-9]*[\.]{LNUM}) | ({LNUM}[\.][0-9]*)
EXPONENT_DNUM ( ({LNUM} | {DNUM}) [eE][+-]? {LNUM})
The size of a float is platform-dependent, although a maximum of ~1.8e308 with a precision of roughly 14 decimal digits is a common value (that's 64 bit IEEE format).

Wednesday, January 16, 2013

Integers

Integers

An integer is a number of the set Z = {..., -2, -1, 0, 1, 2, ...}. 

Syntax

Integers can be specified in decimal (10-based), hexadecimal (16-based) or octal (8-based) notation, optionally preceded by a sign (- or +).
If you use the octal notation, you must precede the number with a 0 (zero), to use hexadecimal notation precede the number with 0x.
Note 11-1. Integer literals
<?php
$a
= 1234; // decimal number$a = -123; // a negative number$a = 0123; // octal number (equivalent to 83 decimal)$a = 0x1A; // hexadecimal number (equivalent to 26 decimal)?>
Formally the possible structure for integer literals is:

decimal     : [1-9][0-9]*
            | 0

hexadecimal : 0[xX][0-9a-fA-F]+

octal       : 0[0-7]+

integer     : [+-]?decimal
            | [+-]?hexadecimal
            | [+-]?octal

Booleans

Booleans

This is the easiest type. A boolean expresses a truth value. It can be either TRUE or FALSE.

Syntax

To specify a boolean literal, use either the keyword TRUE or FALSE. Both are case-insensitive.
<?php
$foo
= True; // assign the value TRUE to $foo?>
 


<?php// == is an operator which test
// equality and returns a boolean
if ($action == "show_version") {
echo
"The version is 1.23";
}
// this is not necessary...if ($show_separators == TRUE) {
echo
"<hr>\n";
}
// ...because you can simply typeif ($show_separators) {
echo
"<hr>\n";
}
?>

PHP Supports Data type


PHP supports eight primitive types.
Four scalar types:
  • boolean
  • integer
  • float (floating-point number, aka 'double')
  • string
Two compound types:
  • array
  • object
And finally two special types:
  • resource
  • NULL
This manual also introduces some pseudo-types for readability reasons:
  • mixed
  • number
  • callback