Home arrow PHP arrow Page 6 - The PHP Scripting Language

Changing Loop Behavior - PHP

This article describes the basics of the PHP scripting language, which is very easy to learn if you are familiar with any programming language. It is excerpted from chapter two of the book Web Database Applications with PHP and MySQL, written by Hugh E. Williams and David Lane (O'Reilly, 2004; ISBN: 0596005431).

TABLE OF CONTENTS:
  1. The PHP Scripting Language
  2. Creating PHP scripts
  3. Character encoding
  4. Expressions, Operators, and Variable Assignment
  5. switch Statement
  6. Changing Loop Behavior
  7. Automatic Type Conversion
  8. User-Defined Functions
  9. Static variables
  10. Managing include files
By: O'Reilly Media
Rating: starstarstarstarstar / 32
September 29, 2005

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

To break out of a loop early—before the loop condition becomes false—the break statement is useful. This example illustrates the idea:

for($x=0; $x<100; $x++)
{
    if ($x > $y)
        break;
    print $x;
}

 If$xreaches 100, the loop terminates normally. However, if$xis (or becomes) greater than$y, the loop is terminated early, and program execution continues after the closing brace of the loop body. Thebreakstatement can be used with all loop types.

To start again from the top of the loop without completing all the statements in the loop body, use thecontinuestatement. Consider this example:

$x = 1;
while($x<100)
{
   print $x;
   $x++;
   if ($x > $y)
      continue;
   print $y;
}

The example prints and increments$xeach time the loop body is executed. If$xis greater than$y, the sequence starts again with theprint $x; statement (and$xkeeps the value that was assigned to it during the loop). Otherwise,$yis printed and the loop begins again normally. Like thebreakstatement,continuecan be used with any loop type.

The use ofbreakandcontinuestatements to change loop behavior makes code harder to understand and should be avoided.

Functions

A function is another concept that programming derived from mathematics. Some programming functions are direct implementations of common mathematical     functions, such as sines and other trigonometric functions. (Naturally, these are not used much in PHP.) But you are sure to use functions related to strings, dates, and other everyday objects in your code. PHP has a large number of useful functions built in, and you can define your own functions as we describe later in this chapter.

Functions are called in PHP scripts and can often be used as expressions. For instance, the following example uses the strtoupper( ) function to change a string to uppercase:

$var = "A string";
print strtoupper($var); // prints "A STRING"

A function is followed by parentheses, which can contain zero or more parameters. This function accepts just one parameter. It can be summarized as follows:

string strtoupper(string subject)

The previous statement is called a prototype and is very useful for introducing functions. Prototypes are used throughout PHP documentation, and the following chapters of this book, when a function is described. The first word indicates what is returned by the function: in this case, its output is a string. The name of the function follows, and then a list of parameters within parentheses. Each parameter is described by a type and a parameter name—strtoupper( ) is defined with a single string parameter named subject. Names allow us to distinguish multiple parameters when we describe the function.

Prototypes use brackets to indicate that function parameters that are optional. Consider the following prototype for the date( ) function:

string date(string format [, integer timestamp])

The date( ) function returns the current date and time as a string where the format is specified by the parameter format. The optional integer parameter timestamp allows non-current dates and times to be formatted. We discuss the date( ) function and timestamps in the next chapter.

When there is more that one optional parameter, then the parameters are shown in nested brackets:

string x(string p1 [, integer p2 [, integer p3]])

The fictional function x( )  must be called with at least p1, but optionally p2 and p3. The nesting of brackets indicates that parameter p3 can’t be included without p2.

Some functions allow an unspecified number of parameters; these are indicated with three periods:

string y(string p1 , ...)

Working with Types

PHP is a loosely typed language, allowing variables and function parameters to be set to any type of data. Similarly, functions can return different data types in different circumstances.

In the last section, we introduced the function prototype as a way of describing the type of parameters that functions are designed to work with and the types of data that are returned. Since PHP is loosely typed, PHP can’t enforce these types as strongly typed languages do. To illustrate this, the PHP library function strtoupper( ) is designed to operate on strings, but can be called with an integer parameter:

$var = 42;
print strtoupper($var); // prints the string "42"

When functions are designed to work with different data types, prototypes describe parameters and return values as mixed. Other functions may not work as expected, or may not work at all, when the wrong type of data is used.

Type Conversion

PHP provides several mechanisms to allow variables of one type to be considered as another type. Variables can be explicitly converted to another type with the following functions:

string strval(mixed variable)
integer intval(mixed variable [, integer base])
float floatval(mixed variable)

The functions convert the variable into a string, integer, or float respectively. The intval( ) function also allows an optional base that determines how the variable is interpreted.

$year = 2003;
// Sets $yearString to the string value "2003"
$yearString = strval($year);
$var = "abc";
// sets $value to the integer0
$value = intval($var);
// sets $count to the integer value 2748 - the
// integer value of "abc" as a hexadecimal number
$count = intval($var, 16);

Because the string"abc"doesn’t look anything like an integer, the first call to the intval( ) function sets$valueto zero.

PHP also supports type conversion with type-casting operators in much the same way as C, to allow the type of an expression to be changed. When you place the type name in parentheses in front of a variable, PHP converts the value to the desired type:

// cast to an integer: the following are equivalent
$int = (int) $var;
$int = (integer) $var;
$int = intval($var);
// cast to a Boolean
$bool = (bool) $var;
$bool = (boolean) $var;
// cast to a float
$float = (float) $var;
$float = floatval($var);
// cast to a string
$str = (string) $var;
$str = strval($var);
// cast to an array
$arr = (array) $var;
// cast to an object
$obj = (object) $var;

In the previous example, type casting, and calls to the strval( ), intval( ), and floatval( ) functions don’t change the value or type of the variable$var. The settype( )function actually modifies the variable that it is called with. For example:

boolean settype(mixed variable, string type)

settype( ) explicitly sets the type of variable to type, where type is one ofarray,boolean,float,integer,object, orstring.

// cast to an integer: the following are equivalent
$var = 39;
// $var is now a string
settype($var, "string");

The rules for converting types are mostly common sense, but some conversions may not appear so straightforward. Table 2-1 shows how various values of$varare converted using the(int),(bool)(string), and(float)casting operators.

Table 2-1.  Examples of type conversion in PHP

 

Value of $var

(int) $var

(bool) $var

(string) $var

(float) $var

null

0

false

""

0

true

1

true

"1"

1

false

0

false

""

0

0

0

false

"0"

0

3.8

3

true

"3.8"

3.8

"0"

0

false

"0"

0

"10"

10

true

"10"

10

"6 feet"

6

true

"6 feet"

6

"foo"

0

true

"foo"

0



 
 
>>> More PHP Articles          >>> More By O'Reilly Media
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: