+ All Categories
Home > Documents > PHP Using Variables and Operators Mohammed M. Hassoun 2012.

PHP Using Variables and Operators Mohammed M. Hassoun 2012.

Date post: 25-Dec-2015
Category:
Upload: abigayle-fox
View: 223 times
Download: 1 times
Share this document with a friend
21
PHP Using Variables and Operators Mohammed M. Hassoun 2012
Transcript

PHP Using Variables and OperatorsMohammed M. Hassoun

2012

Using Variables and Operators

Storing Data in VariablesA variable is simply a container that’s used to store both numeric and

non-numeric

information. And just as with any container, you can move it from

place to place, add stuff to it, or empty it out on the floor in a pile

and fill it with something completely different.

To stretch the analogy a little further, just as it’s a good idea to label

every container, so too should you give every variable in your

program a name. As a general rule, these names should make

sense and should be easy to understand. In the real world, this

makes it easier to find things; in the programming world, it makes

your code cleaner and easier to understand by others. As someone

who’s been there, I can tell you that there’s nothing

more frustrating than spending three hours searching a bunch of

boxes for Mom’s best china, only to realize it’s in the one marked

“Miscellaneous” together with an old rubber bone and some

crumbly biscuits!

PHP has some simple rules for naming variables. Every variable name

must be

preceded with a dollar ($) symbol and must begin with a letter or

underscore character, optionally followed by more letters,

numbers, or underscore characters.

Common punctuation characters, such as commas, quotation

marks, or periods, are not permitted in variable names;

neither are spaces. So, for example, $root, $_num, and $query2

are all valid variable names, while $58%, $1day, and email are all

invalid variable names.

Understanding PHP’s Data TypesThe values assigned to a PHP variable may be of different data types,

ranging from simple string and numeric types to more complex arrays and objects. You’ve already seen two of these, strings and numbers, in action in previous examples. Here’s a full-fledged example, which introduces three more data types:

<?php // Boolean $validUser = true; // integer $size = 15; // floating point $temp = 98.6; // string $cat = 'Siamese'; // null $here = null; ?>

● Booleans are the simplest of all PHP data types. Like a switch that has only two states, on and off, it consists of a single value that may be set to either 1 (true) or 0 (false). In this listing, $validUser is a Boolean variable set to true.

● PHP also supports two numeric data types: integers and floating-point values. Floating-point values (also known as floats or doubles) are decimal or fractional numbers, while integers are round numbers. Both may be less than, greater than, or equal to zero. In this listing, $size holds an integer value, while $temp holds a floating-point value.

● For non-numeric data, PHP offers the string data type, which can hold letters, numbers, and special characters. String values must be enclosed in either single quotes or double quotes. In the previous listing, $cat is a string variable containing the value 'Siamese'.

● You may also encounter the NULL data type, which is a “special” data type first

introduced in PHP 4. NULLs are used to represent “empty” variables in PHP; a variable of type NULL is a variable without any data. In the preceding listing, $here is NULL.

Manipulating Variables with OperatorsBy themselves, variables are simply containers for information. In

order to do anything useful with them, you need operators.

Operators are symbols that tell the PHP processor to perform

certain actions. For example, the addition (+) symbol is an

operator that tells PHP to add two variables or values, while the

greater-than (>) symbol is an operator that tells PHP to compare

two values.

PHP supports more than 50 such operators, ranging from operators

for arithmetical operations to operators for logical comparison and

bitwise calculations. This section discusses the most commonly

used operators.

Performing Arithmetic OperationsPHP supports all standard arithmetic operations, as illustrated by the

list of operators in Table 2-2.

Concatenating StringsTo combine strings, use PHP’s concatenation operator, which happens

to be a period (.). The following example illustrates:<?php // define variables $country = 'England'; $city = 'London';// combine into single string // output: 'Welcome to London, the coolest city in all of England' echo 'Welcome to ' . $city . ', the coolest city in all of ' . $country; ?>

Comparing VariablesPHP lets you compare one variable or value with another via its wide

range of comparison operators, listed in Table 2-3.

It’s worth making special mention here of the === operator. This operator allows for stricter comparison between variables: it only returns true if the two variables or values being compared hold the same information and are of the same data type.

Performing Logical TestsWhen building complex conditional expressions a topic that will be

discussed in detail in Chapter 3 you will often come across situations where it’s necessary to combine one or more logical tests. PHP’s three most commonly used logical operators, listed in Table 2-4, are intended specifically for this situation

.

Other Useful OperatorsThere are a few other operators that tend to come in handy during

PHP development. First, the addition-assignment operator, represented by the symbol +=, lets you simultaneously add and assign a new value to a variable.

Understanding Operator PrecedenceBack in math class, you probably learned about BODMAS, a

mnemonic that specifies the order in which a calculator or a computer performs a sequence of mathematical operations: Brackets, Order, Division, Multiplication, Addition, and Subtraction. Well, PHP follows a similar set of rules when determining which operators have precedence over others—and learning these rules can save you countless frustrating hours debugging a calculation that looks right, yet somehow always returns the wrong result! .The following list (a short version of a much longer list in the PHP manual) illustrates PHP’s most important precedence rules. Operators at the same level have equal precedence.

● ++ --● !● * / %● + - .● < <= > >=● == != === !==● &&● ||● = += -= *= /= .= %= &= |= ^=

Precedence Rules

Handling Form InputSo far, all the examples you’ve seen have had their variables neatly

defined at the top of the script listing. However, as your PHP scripts become more complex, this happy situation will change, and you’ll need to learn how to interact with user-supplied input. The most common source of this information is a Web form, and PHP comes with a simple mechanism to retrieve information submitted through such forms. To illustrate, consider the following simple Web form (choose.html), which asks you to select a brand of automobile and enter your desired color:

<form method="post" action="car.php"> Type: <br /> <select name="selType"> <option value="Porsche 911">Porsche 911</option> <option value="Volkswagen Beetle">Volkswagen Beetle</option> <option value="Ford Taurus">Ford Taurus</option> </select><p /> Color: <br /> <input type="text" name="txtColor" /> <p /> <input type="submit" /> </form>

As forms go, this is a fairly simple one: it has a selection list and an input box.

Figure 2-2 illustrates what it looks like. Notice the 'action' attribute of this Web form: it references a PHP script named car.php. This is the script that receives the data entered into the form once the form is submitted. Notice also the form’s 'method' attribute, which specifies that the submission of data will occur through the POST method. With these two facts firmly in mind, let’s take a look at car.php next:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"

lang="en"> <head><title /></head> <body> <h2>Success!</h2> <?php // get form input $type = $_POST['selType']; $color = $_POST['txtColor']; // use form input echo "Your $color $type is ready. Safe driving!"; ?> </body> </html>

What’s going on here? Well, whenever a form is submitted to a PHP script through the POST method, the form’s input variables and their values automatically become available to the PHP script through a special container variable named $_POST. Accessing the value entered into a particular form field then becomes as simple as referencing $_POST with the corresponding field’s name, as in the preceding script.

Consider, for example, the task of accessing the color entered by the user in the Web form. From the form code, it can be seen that the text input field designated for this data in the form is named 'txtColor'. Therefore, within the PHP script, the value entered into this text input field can be accessed using the syntax $_POST['txtColor'].

This value can then be used in the normal fashion: it may be printed to the Web page, assigned to another variable, or manipulated using one of the many operators discussed in preceding sections.

Figure 2-3 illustrates the result of submitting the form. In case your Web form submits data using the GET method instead of the POST method, PHP has you covered there as well: form input submitted using the GET method finds a home in the $_GET container variable and may be accessed by referencing $_GET

instead of $_POST.

Thank You


Recommended