PHP DevCenter
oreilly.comSafari Books Online.Conferences.

advertisement


PHP Pocket Reference
Pages: 1, 2, 3, 4, 5

Boolean Values

Every value in PHP has a boolean truth value (true or false) associated with it. This value is typically used in control structures, like if/else and for. The boolean value associated with a data value is determined as follows:



  • For an integer or floating point value, the boolean value is false if the value is 0; otherwise the boolean value is true.
  • For a string value, the boolean value is false if the string is empty; otherwise the boolean value is true.
  • For an array, the boolean value is false if the array has no elements; otherwise the boolean value is true.
  • For an object, the boolean value is false if the object has no defined variables or functions; otherwise the boolean value is true.
  • For an undefined object (a variable that has not been defined at all), the boolean value is false.

PHP has two built-in keywords, true and false, where true represents the integer value 1 and false represents the empty string.

Type Casting

Variables in PHP do not need to be explicitly typed. PHP sets the type when a variable is first used in a script. You can explicitly specify a type using C-style casting.

For example:

$var = (int) "123abc";

Without the (int) in this example, PHP creates a string variable. With the explicit cast, however, we have created an integer variable with a value of 123. The following table shows the available cast operators in PHP:

Operators

Function

(int), (integer)

Cast to an integer

(real), (double), (float)

Cast to a floating point number

(string)

Cast to a string

(array)

Cast to an array

(object)

Cast to an object

Although they are not usually needed, PHP does provide the following built-in functions to check variable types in your program: gettype( ), is_long( ), is_double( ), is_string( ), is_array( ), and is_object( ).

Expressions

An expression is the basic building block of the language. Anything with a value can be thought of as an expression. Examples include:

5
5+5
$a
$a==5
sqrt(9)

By combining many of these basic expressions, you can build larger and more complex expressions.

Note that the echo statement we've used in numerous examples cannot be part of a complex expression because it does not have a return value. The print statement, on the other hand, can be used as part of complex expression, as it does have a return value. In all other respects, echo and print are identical--they output data.

Operators

Expressions are combined and manipulated using operators. The following table shows the operators available in PHP, along with their precedence (P) and associativity (A). The following table lists the operators from highest to lowest precedence. These operators should be familiar to you if you have any C, Java, or Perl experience.

Operators

P

A

!, ~, ++, --, @, (the casting operators)

16

Right

*, /, %

15

Left

+, - .

14

Left

<<, >>

13

Left

<, <=, >=, >

12

Non-associative

==, !=

11

Non-associative

&

10

Left

^

9

Left

|

8

Left

&&

7

Left

||

6

Left

? : (conditional operator)

5

Left

=, +=, -=, *=, /=, %=, ^=, .=, &=, |=

4

Left

And

3

Left

Xor

2

Left

Or

1

Left

Control Structures

The control structures in PHP are very similar to those used by the C language. Control structures are used to control the logical flow through a PHP script. PHP's control structures have two syntaxes that can be used interchangeably. The first form uses C-style curly braces to enclose statement blocks, while the second style uses a more verbose syntax that includes explicit ending statements. The first style is preferable when the control structure is completely within a PHP code block. The second style is useful when the construct spans a large section of intermixed code and HTML. The two styles are completely interchangeable, however, so it is really a matter of personal preference which one you use.

if

The if statement is a standard conditional found in most languages. Here are the two syntaxes for the if statement:

if(expr) {	    if(expr):
 statements	     statements
}	            elseif(expr):
elseif(expr) {	     statements
 statements	    else:
}	             statements
else {	            endif;
 statements             
}                  

The if statement causes particular code to be executed if the expression it acts on is true. With the first form, you can omit the braces if you only need to execute a single statement.

switch

The switch statement can be used in place of a lengthy if statement. Here are the two syntaxes for switch:

switch(expr) {         switch(expr):
 case expr:             case expr:
  statements              statements
  break;                 break;
 default:               default:
  statements              statements
  break;                 break;
}                      endswitch;

The expression for each case statement is compared against the switch expression and, if they match, the code following that particular case is executed. The break keyword signals the end of a particular case; it may be omitted, which causes control to flow into the next case. If none of the case expressions match the switch expression, the default case is executed.

while

The while statement is a looping construct that repeatedly executes some code while a particular expression is true:

while(expr) {         while(expr):
 statements             statements
}                     endwhile; 

The while expression is checked before the start of each iteration. If the expression evaluates to true, the code within the loop is executed. If the expression evaluates to false, however, execution skips to the code immediately following the while loop. Note that you can omit the curly braces with the first form of the while statement if you only need to execute a single statement.

It is possible to break out of a running loop at any time using the break keyword. This stops the current loop and, if control is within a nested set of loops, the next outer loop continues. It is also possible to break out of many levels of nested loops by passing a numerical argument to the break statement (break n) that specifies the number of nested loops it should break out of. You can skip the rest of a given loop and go onto the next iteration by using the continue keyword. With continue n, you can skip the current iterations of the n innermost loops.

do/while

The do/while statement is similar to the while statement, except that the conditional expression is checked at the end of each iteration instead of before it:

do { 
 statements
} while(expr);

Note that due to the order of the parts of this statement, there is only one valid syntax. If you only need to execute a single statement, you can omit the curly braces from the syntax. The break and continue statements work with this statement in the same way that they do with the while statement.

for

A for loop is a more complex looping construct than the simple while loop:

for(start_expr; cond_expr; iter_expr) {
 statements
}

for(start_expr; cond_expr; iter_expr): 
 statements
endfor;

A for loop takes three expressions. The first is the start expression; it is evaluated once when the loop begins. This is generally used for initializing a loop counter. The second expression is a conditional expression that controls the iteration of the loop. This expression is checked prior to each iteration. The third expression, the iterative expression, is evaluated at the end of each iteration and is typically used to increment the loop counter. With the first form of the for statement, you can omit the braces if you only need to execute a single statement.

The break and continue statements work with a for loop like they do with a while loop, except that continue causes the iterative expression to be evaluated before the loop conditional expression is checked.

Functions

A function is a named sequence of code statements that can optionally accept parameters and return a value. A function call is an expression that has a value; its value is the returned value from the function. PHP provides a large number of internal functions. The "Function Reference" section lists all of the commonly available functions. PHP also supports user-definable functions. To define a function, use the function keyword. For example:

function soundcheck($a, $b, $c) {
 return "Testing, $a, $b, $c";
}

When you define a function, you need to be careful what name you give it. In particular, you need to make sure that the name does not conflict with any of the internal PHP functions. If you do use a function name that conflicts with an internal function, you get the following error:

Fatal error: Can't redeclare already declared function in filename on line N

After you define a function, you call it by passing in the appropriate arguments. For example:

echo soundcheck(4, 5, 6);

You can also create functions with optional parameters. To do so, you set a default value for each optional parameter in the definition, using C++ style. For example, here's how to make all the parameters to the soundcheck( ) function optional:

function soundcheck($a=1, $b=2, $c=3) {
 return "Testing, $a, $b, $c";
}

Variable Scope

The scope of a variable refers to where in a program the variable is available. If a variable is defined in the main part of a PHP script (i.e., not inside a function or a class), it is in the global scope. Note that global variables are only available during the current request. The only way to make variables in one page available to subsequent requests to another page is to pass them to that page via cookies, GET method data, or PUT method data. To access a global variable from inside a function, you need to use the global keyword. For example:

function test(  ) {
 global $var;
 echo $var;
}
$var="Hello World";
test(  );

The $GLOBALS array is an alternative mechanism for accessing variables in the global scope. This is an associative array of all the variables currently defined in the global scope:

function test(  ) {
 echo $GLOBALS["var"];
}
$var="Hello World";
test(  );

Every function has its own scope. When you create a variable inside of a function, that variable has local scope. In other words, it is only available within the function. In addition, if there is a global variable with the same name as a variable within a function, any changes to the function variable do not affect the value of the global variable.

When you call a function, the arguments you pass to the function (if any) are defined as variables within the function, using the parameter names as variable names. Just as with variables created within a function, these passed arguments are only available within the scope of the function.

Passing Arguments

There are two ways you can pass arguments to a function: by value and by reference. To pass an argument by value, you pass in any valid expression. That expression is evaluated and the value is assigned to the corresponding parameter defined within the function. Any changes you make to the parameter within the function have no effect on the argument passed to the function. For example:

function triple($x) {
 $x=$x*3;
 return $x;
}
$var=10;
$triplevar=triple($var);

In this case, $var evaluates to 10 when triple( ) is called, so $x is set to 10 inside the function. When $x is tripled, that change does not affect the value of $var outside the function.

In contrast, when you pass an argument by reference, changes to the parameter within the function do affect the value of the argument outside the scope of the function. That's because when you pass an argument by reference, you must pass a variable to the function. Now the parameter in the function refers directly to the value of the variable, meaning that any changes within the function are also visible outside the function. For example:

function triple($x) {
 $x=$x*3;
 return $x;
}
$var=10;
triple(&$var);

The & that precedes $var in the call to triple( ) causes the argument to be passed by reference, so the end result is that $var ends up with a value of 30.

Static Variables

PHP supports declaring local function variables as static. A static variable retains its value between function calls, but is still accessible only from within the function it is declared in. Static variables can be initialized and this initialization only takes place the first time the static declaration is executed. Static variables are often used as counters, as in this example:

function hitcount(  ) 
 static $count = 0;
 
 if ($count == 0) {
  print "This is the first time this page";
  print " has been accessed";
 } 
 else {
  print "This page has been accessed $count";
  print  " times";
 }
 $count++;
}

Web-Related Variables

PHP automatically creates global variables for all the data it receives in an HTTP request. This can include GET data, POST data, cookie data, and environment variables. Say you have an HTML form that looks as follows:

<FORM ACTION="test.php3" METHOD="POST">
<INPUT TYPE=text NAME=var>
</FORM>

When the form is submitted to the test.php3 file, the $var variable within that file is set to whatever the user entered in the text field.

A variable can also be set in a URL like this:

http://your.server/test.php3?var=Hello+World

When the request for this URL is processed, the $var variable is set for the test.php3 page.

Any environment variables present in your web server's configuration are also made available, along with any CGI-style variables your web server might set. The actual set of variables varies between different web servers. The best way to get a list of these variables is to use PHP's special information tag. Put the following code in a page and load the page in your browser:

<? phpinfo(  ) ?>

You should see a page with quite a bit of information about PHP and the machine it is running on. There is a table that describes each of the extensions currently enabled in PHP. Another table shows the current values of all the various configuration directives from your php3.ini file. Following those two tables are more tables showing the regular environment variables, the special PHP internal variables, and the special environment variables that your web server has added. Finally, the HTTP request and response headers for the current request are shown.

Sometimes it is convenient to create a generic form handler, where you don't necessarily know all the form element names. To support this, PHP provides GET, POST, and cookie associative arrays that contain all of the data passed to the page using the different techniques. These arrays are named $HTTP_GET_DATA, $HTTP_POST_DATA, $HTTP_COOKIE_DATA, respectively. For example, here's another way to access the value of the text field in our form:

echo $HTTP_POST_VARS["var"];

PHP sets global variables in a particular order. By default, global variables are set first from GET data, then from POST data, and then finally from cookie data. This means that if you have a form with a field named var that uses the GET method and a cookie with a var value, there is just one global variable named $var that has the value of the cookie data. Of course, you can still get at the GET data through the $HTTP_GET_DATA array. The default order can be defined with the gpc_order directive in the php3.ini file.

Pages: 1, 2, 3, 4, 5

Next Pagearrow




Valuable Online Certification Training

Online Certification for Your Career
Earn a Certificate for Professional Development from the University of Illinois Office of Continuing Education upon completion of each online certificate program.

PHP/SQL Programming Certificate — The PHP/SQL Programming Certificate series is comprised of four courses covering beginning to advanced PHP programming, beginning to advanced database programming using the SQL language, database theory, and integrated Web 2.0 programming using PHP and SQL on the Unix/Linux mySQL platform.

Enroll today!


Sponsored by: