the basics of php

30
1 The Basics of PHP PHP is the most popular web-development language in the world.According to esti- mates compiled in April 2004, there are over fifteen million unique domains—and almost two million unique IPs—on the World Wide Web that reside on servers where PHP is supported and used. The term “PHP” is actually a “recursive acronym” that stands for PHP: Hypertext Preprocessor. It might look a bit odd, but it is quite clever, if you think of it. PHP is a “scripting language”—a language intended for interpretation and execution rather than compilation such as, for example, C. The fact that PHP is interpreted and not compiled, however, does not mean that it is incapable of meeting the demands of today’s highly intensive web environments—in fact, a properly written PHP script can deliver incredibly high performance and power. Terms You’ll Need to Understand n Language and Platform n Language construct n Data type n Opening and closing tags n Expression n Variable n Operation and operator precedence n Conditional structures n Iteration and Loops n Functions n Variable variables and variable functions

Upload: others

Post on 22-Jan-2022

8 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: The Basics of PHP

1The Basics of PHP

PHP is the most popular web-development language in the world.According to esti-mates compiled in April 2004, there are over fifteen million unique domains—andalmost two million unique IPs—on the World Wide Web that reside on servers wherePHP is supported and used.

The term “PHP” is actually a “recursive acronym” that stands for PHP: HypertextPreprocessor. It might look a bit odd, but it is quite clever, if you think of it. PHP is a“scripting language”—a language intended for interpretation and execution rather thancompilation such as, for example, C.

The fact that PHP is interpreted and not compiled, however, does not mean that it isincapable of meeting the demands of today’s highly intensive web environments—in fact,a properly written PHP script can deliver incredibly high performance and power.

Terms You’ll Need to Understandn Language and Platformn Language constructn Data typen Opening and closing tagsn Expressionn Variablen Operation and operator precedencen Conditional structuresn Iteration and Loopsn Functionsn Variable variables and variable functions

7090 ch01 6/30/04 1:24 PM Page 1

Page 2: The Basics of PHP

2 Chapter 1 The Basics of PHP

Techniques You’ll Need to Mastern Creating a scriptn Entering PHP moden Handling data typesn Type casting and type jugglingn Creating statementsn Creating operations and expressionsn Writing functionsn Handling conditional statementsn Handling loops

Language and PlatformThe two biggest strengths of PHP are its simplicity and the incredible set of functionalitythat it provides.As a language, it incorporates C’s elegant syntax without the hassle ofmemory and pointer management, as well as Perl’s powerful constructs—without thecomplexity often associated with Perl scripts.

As a platform, PHP provides a powerful set of functions that cover a multitude of dif-ferent needs and capabilities. Programmers who work on commercial platforms such asMicrosoft ASP often marvel at the arsenal of functionality that a PHP developer has athis fingertips without the need to purchase or install anything other than the basic inter-preter package.What’s more, PHP is also extensible through a set of well-defined C APIsthat make it easy for anyone to add more functionality to it as needed.

You have probably noticed that we have made a distinction between “language” and“platform.” By the former, we mean PHP proper—the body of syntactical rules andconstructs that make it possible to create a set of commands that can be executed in aparticular sequence.The latter, on the other hand, is a term that we use to identify thosefacilities that make it possible for the language to perform actions such as communicat-ing with the outside, sending an email, or connecting to a database.

The certification exam verifies your knowledge on both the language and the plat-form—after all, a good programmer needs to know how to write code and how to useall the tools at his disposal. Therefore, it is important that you acquaint yourself withboth aspects of PHP development in order to successfully pass the exam.

Getting StartedThe basic element of a PHP application is the script.A PHP script contains a number ofcommands that the PHP interpreter reads, parses, and executes.

7090 ch01 6/30/04 1:24 PM Page 2

Page 3: The Basics of PHP

3Getting Started

Because PHP is designed to manipulate text files—such as HTML documents—andoutput them, the process of mixing hard-coded textual content and PHP code is facili-tated by the fact that unless you tell it otherwise, the PHP interpreter considers the con-tents of the script file as plain text and outputs them as they are.

It’s only when you explicitly indicate that you are embedding PHP code inside a filethat the interpreter goes to work and starts parsing and executing commands.This isdone by using a special set of opening and closing tags. In part because of historical reasonsand in order to promote maximum flexibility, PHP supports three different sets of tags:

n PHP opening (<?php) and closing (?>) tagsn HTML-style tags (<script language=”php”> and </script>)n “Short” tags: <? and ?>n “ASP-style” tags: <% and %>

The full PHP tags are always available to a script, whereas short tags and ASP-style tagsmight or might not be available to your script, depending on how the particular installa-tion of the PHP interpreter used to execute it is configured.This is made necessary bythe fact that short tags can interfere with XML documents, whereas ASP-style tags caninterfere with other languages that can be used in conjunction with PHP in a chain ofpreprocessors that manipulate a file multiple times before it is outputted.

Let’s take a look at the following sample PHP script:

<html>

<head>

<title>

This is a sample document

</title>

<body>

<?php

echo ‘This is some sample text’;

?>

</body>

</html>

As you can see, this document looks exactly like a normal HTML page until the inter-preter hits the <?php tag, which indicates that text following the tag should be interpret-ed as PHP commands and executed.

Right after the opening tag, we see a line of PHP code, which we’ll examine in detaillater on, followed by the ?> closing tag.After the interpreter sees the closing tag, it stopstrying to parse PHP commands and simply outputs the text as it appears without anychange. Note that, as long as your copy of PHP has been configured to support morethan one type of opening and closing tags, you can mix and match opening and closingtags from different families—for example, <?php echo ‘a’ %> would be a valid script.From a practical perspective, however, doing so would be pointless and confusing—defi-nitely not a good programming practice.

7090 ch01 6/30/04 1:24 PM Page 3

Page 4: The Basics of PHP

4 Chapter 1 The Basics of PHP

Naturally, you can switch between plain-text and PHP execution mode at any pointduring your script and as long as you remember to balance your tags—that is, to closeany tags you open, you can switch an arbitrary number of times.

The special <?= ?> tagsA special set of tags, <?= and ?>, can be used to output the value of an expression direct-ly to the browser (or, if you’re not running PHP in a web environment to the standardoutput).They work by forcing PHP to evaluate the expression they contain and theyoutput its value. For example,

<?= “This is an expression” ?>

Scripts and FilesIt’s important to note that there isn’t necessarily a one-to-one correspondence betweenscripts and files—in fact, a script could be made up of an arbitrary number of files, eachcontaining one or more portions of the code that must be executed. Clearly, this meansthat you can write portions of code so that they can be used by more than one script,such as library, which makes a PHP application even more flexible.

The inclusion of external files is performed using one of four different language con-structs:

n include, which reads an external file and causes it to be interpreted. If the inter-preter cannot find the file, it causes a warning to be produced and does not stopthe execution of the script.

n require, which differs from include in the way it handles failure. If the file to beincluded cannot be found, require causes an error and stops the script’s execu-tion.

n require_once and include_once, which work in a similar way to require andinclude, with one notable difference: No matter how many times you include aparticular file, require_once and include_once will only read it and cause it tobe interpreted once.

The convenience of require_once and include_once is quite obvious because youdon’t have to worry about a particular file being included more than once in any givenscript—which would normally cause problems because everything that is part of the filewould be interpreted more than once. However, generally speaking, situations in which asingle file is included more than once are often an indicator that something is not rightin the layout of your application. Using require_once or include_once will depriveyou of an important debugging aid because you won’t see any errors and, possibly, miss aproblem of larger magnitude that is not immediately obvious. Still, in some cases there isno way around including a file more than once; therefore, these two constructs come invery handy.

7090 ch01 6/30/04 1:24 PM Page 4

Page 5: The Basics of PHP

5Manipulating Data

Let’s try an example.We’ll start with a file that we will call includefile.php:

<?php

echo ‘You have included a file’;

?>

Next, we’ll move on to mainfile.php:<?php

include ‘includefile.php’;

echo ‘I should have included a file.’;

?>

If you make sure to put both files in the same directory and execute mainfile.php, youwill notice that includefile.php is included and executed, causing the text You haveincluded a file to be printed out.

Note that if the two files are not in the same folder, PHP will look for include-file.php in the include path.The include path is determined in part by the environmentin which your script is running and by the php.ini settings that belong to your particularinstallation.

Manipulating DataThe manipulation of data is at the core of every language—and PHP is no exception. Infact, handling information of many different types is very often one of the primary tasksthat a script must perform; it usually culminates with the output of some or all the datato a device—be it a file, the screen, or the Internet.

When dealing with data, it is often very important to know what type of data is beinghandled. If your application needs to know the number of times that a patient has visitedthe hospital, you want to make sure that the information provided by the user is, indeed,a number, and an integer number at that because it would be difficult for anybody tovisit the hospital 3.5 times. Similarly, if you’re asking for a person’s name, you will, at thevery least, ensure that you are not being provided with a number, and so on.

Like most modern languages, PHP supports a variety of data types and is capable ofoperating them in several different ways.

Numeric ValuesPHP supports two numeric data types: integer and real (or floating-point). Both typescorrespond to the classic mathematical definition of the types—with the exception thatreal numbers are stored using a mechanism that makes it impossible to represent certainnumbers, and with a somewhat limited precision so that, for example, 2 divided by 3 isrepresented as 0.66666666666667.

7090 ch01 6/30/04 1:24 PM Page 5

Page 6: The Basics of PHP

6 Chapter 1 The Basics of PHP

Numeric values in base 10 are represented only by digits and (optionally) a dot toseparate units from fractional values.The interpreter does not need commas to group theinteger portion of the value in thousands, nor does it understand it, producing an error ifyou use a format such as 123,456. Similarly, the European representation (comma to sep-arate the fractional part of the value from the integer one) is not supported.

As part of your scripts, you can also enter a value in hexadecimal (base 16) represen-tation—provided that it is prefixed by 0x, and that it is an integer. Both uppercase andlowercase hexadecimal digits are recognized by the interpreter, although traditionallyonly lowercase ones are actually used.

Finally, you can represent an integer value in octal (base 8) notation by prefixing itwith a single zero and using only digits between 0 and 7.Thus, the value 0123 is not thesame as 123.The interpreter will parse 0123 as an octal value, which actually correspondsto 83 in decimal representation (or 0x53 in hexadecimal).

String ValuesAlthough we often think of strings as pieces of text, a string is best defined as a collec-tion of bytes placed in a specific order.Thus, a string could contain text—say, for example,a user’s first and last name—but it could also contain arbitrary binary data, such as thecontents of a JPEG image of a MIDI file.

String values can be declared using one of three methods.The simplest one consists ofenclosing your string in single quotes:

‘This is a simple string’

The information between the quotes will be parsed by the interpreter and stored with-out any modification in the string. Naturally, you can include single quotation marks inyour string by “escaping” them with a backslash:

‘He said: \’This is a simple string\’’

And this also means that, if you want to include a backslash, you will have to escape it aswell:

‘The file is in the c:\\test directory’

Another mechanism used to declare a string uses double quotation marks.This approachprovides a bit more flexibility than the previous one, as you can now include a numberof special characters through specific escape sequences:

n \n—A line feedn \r—A carriage returnn \t—A horizontal tabn \\—A backslashn \”—A double quoten \nnn—A character corresponding to the octal value of nnn (with each digit being

between 0 and 7)n \xnn—A character corresponding to the hexadecimal value of nn

7090 ch01 6/30/04 1:24 PM Page 6

Page 7: The Basics of PHP

7Manipulating Data

Double-quote strings can also contain carriage returns. For example, the followingstrings are equivalent:

“This\nis a string”

“This

is a string”

The final method that you can use to declare a string is through the heredoc syntax:

<<<ENDOFTEXT

My text goes here.

More text can go on another line.

You can even use escape sequences: \t

ENDOFTEXT;

As you can see, the <<< heredoc tag is followed by an arbitrary string of text (whichwe’ll call the marker) on a single line.The interpreter will parse the contents of the file asa string until the marker is found, on its own, at the beginning of a line, followed by asemicolon. Heredoc strings can come in handy when you want to embed large amountsof text in your scripts—although you can sometimes achieve a similar goal by simplyswitching in and out of PHP mode.

Boolean ValuesA Boolean value can only be True or False.This type of value is generally used inBoolean expressions to change the flow of a script’s execution based on certain condi-tions.

Note that, although PHP defines True and False as two valid values when printed,Boolean values are always an empty string (if false) or the number 1 (if true).

ArraysArrays are an aggregate value—that is, they represent a collection of other values. In PHP,arrays can contain an arbitrary number of elements of heterogeneous type (includingother arrays). Each element is assigned a key—another scalar value used to identify theelement within the array.You’ll find this particular data type discussed in greater detail inChapter 4,“Arrays.”

ObjectsObjects are self-contained collections of code and data.They are at the core of object-oriented programming and can provide a very valuable tool for creating solid, enter-prise-level applications.They are described in Chapter 2,“Object-Oriented PHP.”

The NULL Data TypeIt is sometimes important to indicate that a datum has “no value”. Computer languagesneed a special value for this purpose because even zero or an empty string imply that avalue and a type have been assigned to a datum.

The NULL value, thus, is used to express the absence of any type of value.

7090 ch01 6/30/04 1:24 PM Page 7

Page 8: The Basics of PHP

8 Chapter 1 The Basics of PHP

ResourcesA resource is a special type of value that indicates a reference to a resource that is exter-nal to your script and, therefore, not directly accessible from it.

For example, when you open a file so that you can add contents to it, the underlyingcode actually uses the operating system’s functionality to create a file descriptor that canlater be used for manipulating the file.This description can only be accessed by the func-tionality that is built into the interpreter and is, therefore, embedded in a resource valuefor your script to pass when taking advantage of the proper functionality.

Identifiers, Constants, and VariablesOne of the most important aspects of any language is the capability to distinguishbetween its various components.To ensure that the interpreter is capable of recognizingeach token of information passed to it properly, rules must be established for the purposeof being capable to tell each portion apart from the others.

In PHP, the individual tokens are separated from each other through “whitespace”characters, such as the space, tab, and newline character. Outside of strings, these charac-ters have no semantic meaning—therefore, you can separate tokens with an arbitrarynumber of them.With one notable exception that we’ll see in the next section, alltokens are not case sensitive—that is, echo is equivalent to Echo, or even eCHo.

Identifiers, which, as their name implies, are used as a label to identify data elementsor groups of commands, must be named as follows:

n The first character can either be a letter or an underscore.n Characters following the second can be an arbitrary combination of letters, digits,

and underscores.

Thus, for example, the following are all valid identifiers:n __anidentifier

n yet_another_identifier___

n _3_stepsToSuccess

VariablesAs you can imagine, a language wouldn’t be very useful if all it could deal with wereimmediate values: Using it would be a bit like buying a car with no doors or windows—sure, it can run fast, but to what purpose?

Similar to almost every computer language, PHP provides a facility known as a “vari-able” capable of containing data. PHP variables can contain one value at a time(although that value could, for example, be an array, which itself is a container for anarbitrary number of other values).

7090 ch01 6/30/04 1:24 PM Page 8

Page 9: The Basics of PHP

9Identifiers, Constants, and Variables

Variables are identifiers preceded by a dollar sign ($).Therefore, they must respect allthe rules that determine how an identifier can be named.Additionally, variable names arecase sensitive, so $myvar is different from $MyVar.

Unlike other languages, PHP does not require that the variables used by a script bedeclared before they can be used.The interpreter will create variables as they are usedthroughout the script.

Although this translates in a high degree of flexibility and generally nimbler scripts, itcan also cause plenty of frustration and security issues.A simple spelling mistake, forexample, could turn a reference to $myvar to, say, $mvvar, thus causing your script to ref-erence a variable that doesn’t exist. Similarly, if the installation of PHP that you are run-ning has register_globals set to true, a malicious user will be able to set variables inyour script to arbitrary values unless you take the proper precautions—more about thatlater in this chapter.

Variable Substitution in StringsBoth the double-quote and heredoc syntaxes support the ability to embed the value of avariable directly in a string:

“The value of \$a is $a”

In the preceding string, the second instance of $a will actually be replaced by the valueof the $a variable, whereas the first instance will not because the dollar sign is escaped bya backslash.

For those cases in which this simple syntax won’t work, such as when there is nowhitespace between the name of the variable whose value you want to extract and theremainder of the string, you can forcefully isolate the data to be replaced by using braces:

<?

$thousands = 100;

echo “There are {$thousands}000 values”;

?>

StatementsA statement corresponds to one command that the interpreter must execute.This couldbe an expression, a call to another block of code, or one of several constructs that PHPdefines. For example, the echo construct causes the value of an expression to be sent tothe script’s output device.

Statements always end in a semicolon—if they don’t, the system will output a parsingerror.

7090 ch01 6/30/04 1:24 PM Page 9

Page 10: The Basics of PHP

10 Chapter 1 The Basics of PHP

ConstantsAs their name implies, constants are data holders whose type and value doesn’t change.

A constant is create by using the define() construct. Here’s an example:

<?php

define (“SOME_CONSTANT”, 28);

echo SOME_CONSTANT;

?>

As you can see, define() takes two parameters; the first, a string, indicates the name ofthe constant, whereas the second indicates its value.After you have defined a constant,you can use it directly from your code, as we have done here.This means that although,in theory, you can define a constant with an arbitrary name, you will only be able to useit if that name follows the identifier naming rules that we discussed in the previoussections.

OperatorsVariables, constants, and data types are not very useful if you can’t combine and manipu-late them in a variety of ways. In PHP, one of these ways is through operators.

PHP recognizes several classes of operators, depending on what purpose they are usedfor.

The Assignment OperatorThe assignment operator = is used to assign a value to a variable:

$a = 10;

$c = “Greetings Professor Faulken”;

$test = false;

It’s very important to understand that, by default, variables are assigned by value.Thismeans that the following

$a = $b

Assigns the value of $b to $a. If you change $b after the assignment has taken place, $awill remain the same.This might not always be what you actually want to happen—youmight need to link $a and $b so that a change to the latter is also reflected in the latter.You can do so by assigning to $a a reference to $b:

$a = &$b

Any change to $b will now also be reflected in $a.

7090 ch01 6/30/04 1:24 PM Page 10

Page 11: The Basics of PHP

11Operators

Arithmetic OperatorsPerhaps the class of operators that most newcomers to PHP most readily identify with isthe one that includes arithmetic operations.These are all part of binary operations(meaning that they always include two operators):

n Addition (+)n Subtraction (-)n Multiplication (*)n Division (/)n Modulus (%)

Operations are written using the infix notation that we are all used to. For example,

5 + 4

2 * $a

Keep in mind that the modulus operation works a bit different from the typical mathe-matical operation because it returns a signed value rather than an absolute one.

PHP also borrows four special incrementing/decrementing operators from the C language:

n The prefix incrementing operator ++ increments the value of the variable that suc-ceeds it, and then returns its new value. For example, ++$a

n The postfix incrementing operator ++ returns the value of the variable that pre-cedes it, and then increments its value. For example, $a++

n The prefix decrementing operator — decrements the value of the variable that suc-ceeds it, and then returns its new value. For example, —$a

n The postfix decrementing operator — returns the value of the variable that pre-cedes it, and then decrements its value. For example, $a—

The difference between the prefix and postfix version of the operators is sometimes dif-ficult to grasp, but generally speaking is quite simple:The prefix version changes thevalue of the variable first, and then returns its value.This means that if the value of $a is1, ++$a will first increment $a by one, and then return its value (which will be 2).Conversely, the postfix version returns the value first and then modifies it—so, if $a is 1,$a++ will first return 1 and then increment $a to 2.

Unary incrementing and decrementing operations can be extremely helpful becausethey enable for the modification of a variable in an atomic way and can easily be com-bined with other operations. However, this doesn’t mean that they should be abused, asthey can make the code more difficult to read.

7090 ch01 6/30/04 1:24 PM Page 11

Page 12: The Basics of PHP

12 Chapter 1 The Basics of PHP

Bitwise OperatorsThis class of operators manipulates the value of variables at the bit level:

n The bitwise AND (&)operation causes the value of a bit to be set if it is set in boththe left and right operands. For example, 1 & 1 = 1, whereas 1 & 2 = 0.

n The bitwise OR (|) operation causes the value of a bit to be set if it is set ineither the left or right operands. For example, 1 | 1 = 1 and 1 | 2 = 3.

n The bitwise XOR (^) operation causes the value of a bit to be set if it is set ineither the left or right operands, but not in both. For example, 1 ^ 1 = 0, 1 ^ 0= 1.

n The bitwise NOT (~)operation causes the bits in its operand to be reversed—thatis, set if they are not and unset otherwise. Keep in mind that if you’re dealing withan integer number, all the bits of that integer number will be reversed providing avalue that you might not expect. For example, on a 32-bit IBM platform, whereeach integer is represented by a single 32-bit value, ~0 = -1, because the integer issigned.

n The bitwise >)>>)>left-shift (<<) and right-shift (>>) operators actually shift thebits of the left operands left or right by the number of positions specified by theright operand. For example, 4 >> 1 = 2, whereas 2 << 1 = 4. On integer values,shifting bits to the left by n positions corresponds to multiplying the left operandby 2n, whereas shifting them right by n position corresponds to dividing the leftoperand by 2n.

Remember that bitwise operations can only be performed on integer values. If you use avalue of a different type, PHP will convert it for you as appropriate or output an error ifit can’t.

Error-control OperatorsPHP is normally very vocal when it finds something wrong with the code it’s interpret-ing and executing, outputting verbose and helpful error messages to mark the occasion.Sometimes, however, it’s practical to ensure that no error be reported, even if an errorcondition occurs.

This can be accomplished by using the error-suppression operator @ in front of theoperation you want to perform. For example, the following would normally print anerror because the result of a division by zero is infinity—a number that cannot be repre-sented by any of the PHP data types.With the @ operator, however, we can prevent theerror from being printed out (but not from occurring):

<?php

@$a = 1 / 0;

?>

7090 ch01 6/30/04 1:24 PM Page 12

Page 13: The Basics of PHP

13Operators

This operator can be very dangerous because it prevents PHP from notifying you thatsomething has gone wrong.You should, therefore, use it only whenever you want to pre-vent errors from propagating to a default handler because you have a specialized codesegment that you want to take care of the problem. Generally speaking, it’s a bad idea touse this approach simply as a way to “silence” the PHP interpreter, as there are betterways to do so (for example, through error logging) without compromising its errorreporting capabilities.

Note that not all types of errors can be caught and suppressed using the @ operator.Because PHP first parses your script into an intermediate language that makes executionfaster and then executes it, it won’t be capable of knowing that you have requested errorsuppression until the parsing phase is over and the execution phase begins.As a result,syntax errors that take place during the parsing phase will always result in an error beingoutputted, unless you have changed your php.ini settings in a way that prevents all errorsfrom being outputted independently from your use of the @ operator.

String OperatorsWhen it comes to manipulating strings, the only operator available is the concatenationoperator, identified by a period (.).As you might imagine, it concatenates two stringsinto a third one, which is returned as the operation’s result:

<?php

$a = ‘This is string ‘;

$b = $a . “is complete now.”;

?>

Comparison OperatorsComparison operators are used to determine the relationship between two operands.The result of a comparison is always a Boolean value:

n The == operator determines if two values are equal. For example, 10 == 10n The != operator determines if two values are different. For example, 10 != 11n The < operator determines whether the left operand’s value is less than the right

operand’s.n The > operator )>)>) operator>determines whether the left operand’s value is

greater than the right operand’s.n The <= operator determines whether the left operand’s value is less than or equal

to the right operand’s.n The >= operator=)>=)>=) operator> determines whether the left operand’s value

is greater than the right operand’s.

7090 ch01 6/30/04 1:24 PM Page 13

Page 14: The Basics of PHP

14 Chapter 1 The Basics of PHP

To facilitate the operation of comparing two values, PHP will “automagically” perform aset of conversions to ensure that the two operands being compared will have the sametype.

Thus, if you compare the number 10 with the string “10”, PHP will first convert thestring to an integer number and then perform the comparison, whereas if you comparethe integer 10 to the floating-point number 11.4, the former will be converted to afloating-point number first.

For the most part, this feature of PHP comes in very handy. However, in some cases itopens up a few potentially devastating pitfalls. For example, consider the string “test”. Ifyou compare it against the number 0, PHP will first try to convert it to an integer num-ber and, because test contains no digits, the result will be the value 0. Now, it mightnot matter that the conversion took place, but if, for some reason, you really needed thecomparison to be between two numbers, you will have a problem: “11test” comparedagainst 11 will return True—and that might not exactly be what you were expecting!

Similarly, a 0 value can give you trouble if you’re comparing a number against aBoolean value because False will be converted to 0 (and vice versa).

For those situations in which both the type and the value of a datum are both rele-vant to the comparison, PHP provides two “identity” operators:

n The === operator determines whether the value and the type of the two operandsis the same.

n The !== operator determines whether either the value or the type of the twooperands is different.

Thus, while 10 == “10”, 10 !== “10”.

Logical OperatorsLogical operators are often used in conjunction with comparison operators to createcomplex decision mechanisms.They also return a Boolean result:

n The AND operator (indicated by the keyword and or by &&) returns True if boththe left and right operands cannot be evaluated to False

n The OR operator (indicated by the keyword or or by ||) returns True if eitherthe left or right operand cannot be evaluated as False

n The XOR operator (indicated by the keyword xor) returns True if either the leftor right operand can be evaluated as True, but not both.

n The unary NOT operator (indicated by !) returns False if the operand can beevaluated as True, and True otherwise.

Note that we used the term “can be evaluated as” rather than “is.”This is because, even ifone of the operands is not a Boolean value, the interpreter will try to convert it and useit as such.Thus, any number different from 0 is evaluated as True, as is every string thatis not empty or is not ‘0’.

7090 ch01 6/30/04 1:24 PM Page 14

Page 15: The Basics of PHP

15Operators

TypecastingEven though PHP handles data types automatically most of the time, you can still forceit to convert a particular datum to a specific type by using a typecasting operator.Theseare

n (int) to cast a value to its integer equivalentn (float) to cast a value to its floating-point equivalentn (string) to cast a value to its string equivalentn (array) to force the conversion of the operand to an array if it is not one alreadyn (object) to force the conversion of the operand to an object if it is not one

already

Keep in mind that some of these conversions fall prey to the same pitfalls that we dis-cussed earlier for automatic conversions performed during comparisons.

Combined Assignment OperatorsA particular class of operators combines the assignment of a value with another opera-tion. For example, += causes the left-hand operator to be added to the right-hand opera-tor, and the result of the addition stored back in to the left-hand operator (which must,therefore, be a variable). For example,

<?php

$a = 1;

$a += 5;

?>

At the end of the previous script’s execution, $a will have a value of 6.All the binaryarithmetic and bitwise operators can be part of one of these combined assignment oper-ations.

Combining Operations: Operator Precedence and AssociativityOperator precedence determines in what order multiple combined operations that arepart of the same expression are executed. For example, one of the basic rules of arith-metic is that multiplications and divisions are executed before additions and subtractions.With a large number of types of operations available, things get a bit more complicated,but are by no means complex.

When two operations having the same precedence must be performed one after theother, the concept of associativity comes in to play.A left-associative operation is executedfrom left to right. So, for example, 3 + 5 + 4 = (3 + 5) + 4.A right-associative

7090 ch01 6/30/04 1:24 PM Page 15

Page 16: The Basics of PHP

16 Chapter 1 The Basics of PHP

operation, on the other hand, is executed from right to left: $a += $b += 10 is equiva-lent to $a += ($b += 10).There are also some non-associative operations, such as com-parisons. If two non-associative operations are on the same level of an expression, anerror is produced. (If you think about it, an expression such as $a <= $b >= $c makesno sense in the context of a PHP script because the concept of “between” is not definedin the language.You would, in fact, have to rewrite that as ($a <= $b) && ($b >=$c).) Table 1.1 shows a list of operator precedences and associativity. Note that some ofthe operators will be introduced in Chapters 2 and 4.

Table 1.1 Operator Precedence

Associativity Operator

right [

right ! ~ ++ — (int) (float)

(string) (array) (object) @

left * / %

left << >>

non-associative < <= > >=

non-associative == != === !==

left &

left ^

left |

left &&

left ||

left ? :

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

<<= >>=

right print

left and

left xor

left or

left ,

As you have probably noticed, the logical operators && and || have a different prece-dence than and and or.This is an important bit of information that you should keep inmind while reading through PHP code.

Operator precedence can be overridden by using parentheses. For example,

10 * 5 + 2 = 52

10 & (5 + 2) = 70

Parentheses can be nested to an arbitrary number of levels—but, of course, the numberof parentheses in an expression must be balanced.

7090 ch01 6/30/04 1:24 PM Page 16

Page 17: The Basics of PHP

17Conditional Structures

Conditional StructuresIt is often necessary, at some point, to change the execution of a script based on one ormore conditions. PHP offers a set of structures that can be used to control the flow ofexecution as needed.

The simplest such structure is the if-then-else statement:

if (condition1)

code-block-1

[else

code-block-2...]

The series of commands code-block-1 is executed if condition1 can be evaluated tothe Boolean value True, whereas code-block-2 is executed if condition1 can be evalu-ated to False. For example,

<?php

$a = 10;

if ($a < 100)

echo ‘Less than 100’;

else

echo ‘More than 100’;

?>

In this case, the value of $a is obviously less than one hundred and, therefore, the firstblock of code will be executed, outputting Less than 100.

Clearly, if you could only include one instruction in every block of code, PHP wouldbe extremely inefficient. Luckily, multiple instructions can be enclosed within braces:

<?php

$a = 10;

if ($a < 100)

{

echo ‘Less than 100’;

echo “\nNow I can output more than one line!”;

}

else

echo ‘More than 100’;

?>

7090 ch01 6/30/04 1:24 PM Page 17

Page 18: The Basics of PHP

18 Chapter 1 The Basics of PHP

if-then-else statements can be nested to an arbitrary level. PHP even supports a spe-cial keyword, elseif, that makes this process easier:

<?php

$a = 75;

if ($a > 100)

{

echo ‘More than 100’;

echo “Now I can output more than one line!”;

}

elseif ($a > 50)

echo ‘More than 50’;

else

echo “I don’t know what it is”;

?>

In this case, the first condition ($a > 100) will not be satisfied.The execution pointwill then move on to the second condition, ($a > 50), which will be satisfied, causingthe interpreter to output More than 50.

Alternative if-then-else SyntaxAs an alternative to the if-then-else syntax described in the previous section, which iswhat you will see in most modern PHP programs, PHP supports a different syntax inwhich code blocks start with a semicolon and end with the keyword endif:

<?php

$a = 10;

if ($a < 100):

echo ‘Less than 100’;

echo “Now I can output more than one line!”;

elseif ($a < 50):

echo ‘Less than fifty’;

else:

echo “I don’t know what it is”;

endif

?>

Short-form if-then-elseA simple if-then-else statement can actually be written using a ternary operator (and,therefore, inserted directly into a more complex operation):

7090 ch01 6/30/04 1:24 PM Page 18

Page 19: The Basics of PHP

19Conditional Structures

<?

$n = 15;

$a = ($n % 2 ? ‘odd number’ : ‘even number’);

echo $a;

?>

As you can see, the ternary operator’s syntax is

(condition ? value_if_true : value_if_false)

In the specific case here, the value_if_true is returned by the expression if conditionevaluates to True; otherwise, value_if_false is returned instead.

The case StatementA complex if-then-else statement, composed of an arbitrary number of conditions allbased on the same expression being compared to a number of immediate values, canactually be replaced by a case statement as follows:

<?php

$a = 10;

switch ($a)

{

case ‘1’:

echo ‘1’;

break;

case ‘5’:

echo ‘Five’;

break;

case ‘Ten’:

echo ‘String 10’;

break;

case 10:

echo ‘10’;

break;

7090 ch01 6/30/04 1:24 PM Page 19

Page 20: The Basics of PHP

20 Chapter 1 The Basics of PHP

default:

echo ‘I don\’t know what to do’;

break;

}

?>

When the interpreter encounters the switch keyword, it evaluates the expression thatfollows it and then compares the resulting value with each of the individual case condi-tions. If a match is found, the code is executed until the keyword break or the end ofthe switch code block is found, whichever comes first. If no match is found and thedefault code block is present, its contents are executed.

Note that the presence of the break statement is essential—if it is not present, theinterpreter will continue to execute code in to the next case or default code block,which often (but not always) isn’t what you want to happen.You can actually turn thisbehavior to your advantage to simulate a logical or operation; for example, this code

<?php

if ($a == 1 || $a == 2)

{

echo ‘test one’;

}

else

{

echo ‘test two’;

}

?>

Could be rewritten as follows:<?php

switch ($a)

{

case 1:

case 2:

echo ‘test one’;

break;

default:

echo ‘test two’;

break;

}

?>

7090 ch01 6/30/04 1:24 PM Page 20

Page 21: The Basics of PHP

21Iteration and Loops

Once inside the switch statement, a value of 1 or 2 will cause the same actions to takeplace.

Iteration and LoopsScripts are often used to perform repetitive tasks.This means that it is sometimes neces-sary to cause a script to execute the same instructions for a number of times thatmight—or might not—be known ahead of time. PHP provides a number of controlstructures that can be used for this purpose.

The while StructureA while statement executes a code block until a condition is set:

<?php

$a = 10;

while ($a < 100)

{

$a++;

}

?>

Clearly, you can use a condition that can never be satisfied—in which case, you’ll end upwith an infinite loop. Infinite loops are usually not a good thing, but, because PHP pro-vides the proper mechanism for interrupting the loop at any point, they can also be use-ful. Consider the following:

<?php

$a = 10;

$b = 50;

while (true)

{

$a++;

if ($a > 100)

{

$b++;

if ($b > 50)

{

break;

}

}

}

?>

7090 ch01 6/30/04 1:24 PM Page 21

Page 22: The Basics of PHP

22 Chapter 1 The Basics of PHP

In this script, the (true) condition is always satisfied and, therefore, the interpreter willbe more than happy to go on repeating the code block forever. However, inside the codeblock itself, we perform two if-then checks, and the second one is dependent on the firstso that the $b > 50 will only be evaluated after $a > 100, and, if both are true, thebreak statement will cause the execution point to exit from the loop into the precedingscope. Naturally, we could have written this loop just by using the condition ($a <=100 && $b <= 50) in the while loop, but it would have been less efficient because we’dhave to perform the check twice. (Remember, $b doesn’t increment unless $a is greaterthan 100.) If the second condition were a complex expression, our script’s performancemight have suffered.

The do-while StructureThe big problem with the while() structure is that, if the condition never evaluates toTrue, the statements inside the code block are never executed.

In some cases, it might be preferable that the code be executed at least once, and thenthe condition evaluated to determine whether it will be necessary to execute it again.This can be achieved in one of two ways: either by copying the code outside of thewhile loop into a separate code block, which is inefficient and makes your scripts moredifficult to maintain, or by using a do-while loop:

<?php

$a = 10;

do

{

$a++;

}

while ($a < 10);

?>

In this simple script, $a will be incremented by one once—even if the condition in thedo-while statement will never be true.

The for LoopWhen you know exactly how many times a particular set of instructions must be repeat-ed, using while and do-while loops is a bit inconvenient. For this purpose, for loops arealso part of the arsenal at the disposal of the PHP programmer:

<?php

for ($i = 10; $i < 100; $i++)

{

7090 ch01 6/30/04 1:24 PM Page 22

Page 23: The Basics of PHP

23Iteration and Loops

echo $i;

}

?>

As you can see, the declaration of a for loop is broken in to three parts:The first is usedto perform any initialization operations needed and is executed only once before the loopbegins.The second represents the condition that must be satisfied for the loop to contin-ue. Finally, the third contains a set of instructions that are executed once at the end ofevery iteration of the loop before the condition is tested.

A for loop could, in principle, be rewritten as a while loop. For example, the previ-ous simple script can be rewritten as follows:

<?php

$i = 10;

while ($i < 100)

{

echo $i;

$i++;

}

?>

As you can see, however, the for loop is much more elegant and compact.Note that you can actually include more than one operation in the initialization and

end-of-loop expressions of the for loop declaration by separating them with a comma:

<?php

for ($i = 1, $c = 2; $i < 10; $i++, $c += 2)

{

echo $i;

echo $c;

}

?>

Naturally, you can also create a for loop that is infinite—in a number of ways, in fact.You could omit the second expression from the declaration, which would cause theinterpreter to always evaluate the condition to true.You could omit the third expressionand never perform any actions in the code block associated with the loop that will causethe condition in the second expression to be evaluated as true.You can even omit allthree expressions using the form for(;;) and end up with the equivalent ofwhile(true).

7090 ch01 6/30/04 1:24 PM Page 23

Page 24: The Basics of PHP

24 Chapter 1 The Basics of PHP

Continuing a LoopYou have already seen how the break statement can be used to exit from a loop.Whatif, however, you simply want to skip until the end of the code block associated with theloop and move on to the next iteration?

In that case, you can use the continue statement:

<?php

for ($i = 1, $c = 2; $i < 10; $i++, $c += 2)

{

if ($c < 10)

continue;

echo ‘I\’ve reached 10!’;

}

?>

If you nest more than one loop, you can actually even specify the number of loops thatyou want to skip and move on from:

<?php

for ($i = 1, $c = 2; $i < 10; $i++, $c += 2)

{

$b = 0;

while ($b < 199) {

if ($c < 10)

continue 2;

echo ‘I\’ve reached 10!’;

}

}

?>

In this case, when the execution reaches the inner while loop, if $c is less than 10, thecontinue 2 statement will cause the interpreter to skip back two loops and start overwith the next iteration of the for loop.

Functions and ConstructsThe code that we have looked at up to this point works using a very simple top-downexecution style:The interpreter simply starts at the beginning and works its way to theend in a linear fashion. In the real world, this simple approach is rarely practical; forexample, you might want to perform a certain operation more than once in differentportions of your code.To do so, PHP supports a facility known as a function.

7090 ch01 6/30/04 1:24 PM Page 24

Page 25: The Basics of PHP

25Functions and Constructs

Functions must be declared using the following syntax:

function function_name ([param1[, paramn]])

As you can see, each function is assigned a name and can receive one or more parame-ters.The parameters exist as variables throughout the execution of the entire function.

Let’s look at an example:

<?php

function calc_weeks ($years)

{

return $years * 52;

}

$my_years = 28;

echo calc_weeks ($my_years);

?>

The $years variable is created whenever the calc_weeks function is called and initial-ized with the value passed to it.The return statement is used to return a value from thefunction, which then becomes available to the calling script.You can also use return toexit from the function at any given time.

Normally, parameters are passed by value—this means that, in the previous example, acopy of the $my_years variable is placed in the $years variable when the functionbegins, and any changes to the latter are not reflected in the former. It is, however, possi-ble to force passing a parameter by reference so that any changes performed within thefunction to it will be reflected on the outside as well:

<?php

function calc_weeks (&$years)

{

$my_years += 10;

return $my_years * 52;

}

$my_years = 28;

echo calc_weeks ($my_years);

?>

You can also assign a default value to any of the parameters of a function when declaringit.This way, if the caller does not provide a value for the parameter, the default one willbe used instead:

7090 ch01 6/30/04 1:24 PM Page 25

Page 26: The Basics of PHP

26 Chapter 1 The Basics of PHP

<?php

function calc_weeks ($my_years = 10)

{

return $my_years * 52;

}

echo calc_weeks ();

?>

In this case, because no value has been passed for $my_years, the default of 10 will beused by the interpreter. Note that you can’t assign a default value to a parameter passedby reference.

Functions and Variable ScopeIt’s important to note that there is no relationship between the name of a variabledeclared inside a function and any corresponding variables declared outside of it. In PHP,variable scope works differently from most other languages so that what resides in theglobal scope is not automatically available in a function’s scope. Let’s look at an example:

<?php

function calc_weeks ()

{

$years += 10;

return $years * 52;

}

$years = 28;

echo calc_weeks ();

?>

In this particular case, the script assumes that the $years variable, which is part of theglobal scope, will be automatically included in the scope of calc_weeks(). However, thisdoes not take place, so $years has a value of Null inside the function, resulting in areturn value of 0.

If you want to import global variables inside a function’s scope, you can do so byusing the global statement:

<?php

function calc_weeks ()

{

global $years;

7090 ch01 6/30/04 1:24 PM Page 26

Page 27: The Basics of PHP

27Functions and Constructs

$years += 10;

return $years * 52;

}

$years = 28;

echo calc_weeks ();

?>

The $years variable is now available to the function, where it can be used and modi-fied. Note that by importing the variable inside the function’s scope, any changes madeto it will be reflected in the global scope as well—in other words, you’ll be accessing thevariable itself, and not an ad hoc copy as you would with a parameter passed by value.

Functions with Variable ParametersIt’s sometimes impossible to know how many parameters are needed for a function. Inthis case, you can create a function that accepts a variable number of arguments using anumber of functions that PHP makes available for you:

n func_num_args() returns the number of parameters passed to a function.n func_get_arg($arg_num) returns a particular parameter, given its position in the

parameter list.n func_get_args() returns an array containing all the parameters in the parameter

list.

As an example, let’s write a function that calculates the arithmetic average of all theparameters passed to it:

<?php

function calc_avg()

{

$args = func_num_args();

if ($args == 0)

return 0;

$sum = 0;

for ($i = 0; $i < $args; $i++)

$sum += func_get_arg($i);

return $sum / $args;

}

echo calc_avg (19, 23, 44, 1231, 2132, 11);

?>

7090 ch01 6/30/04 1:24 PM Page 27

Page 28: The Basics of PHP

28 Chapter 1 The Basics of PHP

As you can see, we start by determining the number of arguments and exiting immedi-ately if there are none.We need to do so because otherwise the last instruction wouldcause a division-by-zero error. Next, we create a for loop that simply cycles througheach parameter in sequence, adding its value to the sum. Finally, we calculate and returnthe average value by dividing the sum by the number of parameters. Note how westored the value of the parameter count in the $args variable—we did so in order tomake the script a bit more efficient because otherwise we would have had to perform acall to func_get_args() for every cycle of the for loop. That would have been ratherwasteful because a function call is quite expensive in terms of performance and thenumber of parameters passed to the function does not change during its execution.

Variable Variables and Variable FunctionsPHP supports two very useful features known as “variable variables” and “variable func-tions.”

The former allows you use the value of a variable as the name of a variable. Soundconfusing? Look at this example:

<?

$a = 100;

$b = ‘a’;

echo $$b;

?>

When this script is executed and the interpreter encounters the $$b expression, it firstdetermines the value of $b, which is the string a. It then reevaluates the expression witha substituted for $b as $a, thus returning the value of the $a variable.

Similarly, you can use a variable’s value as the name of a function:

<?

function odd_number ($x)

{

echo “$x is odd”;

}

function even_number ($x)

{

echo “$x is even”;

}

$n = 15;

$a = ($n % 2 ? ‘odd_number’ : ‘even_number’);

7090 ch01 6/30/04 1:24 PM Page 28

Page 29: The Basics of PHP

29Exam Prep Questions

$a($n);

?>

At the end of the script, $a will contain either odd_number or even_number.The expres-sion $a($n) will then be evaluated as a call to either odd_number() or even_number().

Variable variables and variable functions can be extremely valuable and convenient.However, they tend to make your code obscure because the only way to really tell whathappens during the script’s execution is to execute it—you can’t determine whetherwhat you have written is correct by simply looking at it.As a result, you should onlyreally use variable variables and functions when their usefulness outweighs the potentialproblems that they can introduce.

Exam Prep Questions1. What will the following script output?

<?php

$x = 3 - 5 % 3;

echo $x;

?>

A. 2

B. 1

C. Null

D. True

E. 3

Answer B is correct. Because of operator precedence, the modulus operation isperformed first, yielding a result of 2 (the remainder of the division of 5 by 2).Then, the result of this operation is subtracted from the integer 3.

2. Which data type will the $a variable have at the end of the following script?

<?php

$a = “1”;

echo $x;

?>

7090 ch01 6/30/04 1:24 PM Page 29

Page 30: The Basics of PHP

30 Chapter 1 The Basics of PHP

A. (int) 1

B. (string) “1”

C. (bool) True

D. (float) 1.0

E. (float) 1

Answer B is correct.When a numeric string is assigned to a variable, it remains a string, and it is not converted until needed because of an operation that requires so.

3. What will the following script output?

<?php

$a = 1;

$a = $a— + 1;

echo $a;

?>

A. 2

B. 1

C. 3

D. 0

E. Null

Answer A is correct.The expression $a— will be evaluated after the expression $a= $a + 1 but before the assignment.Therefore, by the time $a + 1 is assigned to$a, the increment will simply be lost.

7090 ch01 6/30/04 1:24 PM Page 30