Wednesday, August 8, 2012

PHP: Integers Syntax

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


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.

Example 2.1. Integer literals

$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

The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that's 32 bits signed). PHP does not support unsigned integers.

Integer overflow

If you specify a number beyond the bounds of the integer type, it will be interpreted as a float instead. Also, if you perform an operation that results in a number beyond the bounds of the integer type, a float will be returned instead.

$large_number =  2147483647;
// output: int(2147483647)

$large_number =  2147483648;
// output: float(2147483648)

// this goes also for hexadecimal specified integers:
var_dump( 0x80000000 );
// output: float(2147483648)

$million = 1000000;
$large_number =  50000 * $million;
// output: float(50000000000)

Unfortunately, there was a bug in PHP so that this does not always work correctly when there are negative numbers involved. For example: when you do -50000 * $million, the result will be -429496728. However, when both operands are positive there is no problem.

This is solved in PHP 4.1.0.
There is no integer division operator in PHP. 1/2 yields the float 0.5. You can cast the value to an integer to always round it downwards, or you can use the round() function.

var_dump(25/7);         // float(3.5714285714286)
var_dump((int) (25/7)); // int(3)
var_dump(round(25/7));  // float(4)

Converting to integer

To explicitly convert a value to integer, use either the (int) or the (integer) cast. However, in most cases you do not need to use the cast, since a value will be automatically converted if an operator, function or control structure requires an integer argument. You can also convert a value to integer with the function intval().
See also type-juggling.

From booleans

FALSE will yield 0 (zero), and TRUE will yield 1 (one).

From floating point numbers

When converting from float to integer, the number will be rounded towards zero.
If the float is beyond the boundaries of integer (usually +/- 2.15e+9 = 2^31), the result is undefined, since the float hasn't got enough precision to give an exact integer result. No warning, not even a notice will be issued in this case!
Never cast an unknown fraction to integer, as this can sometimes lead to unexpected results.

echo (int) ( (0.1+0.7) * 10 ); // echoes 7!

See for more information the warning about float-precision.

From strings

See String conversion to numbers

From other types

Behaviour of converting to integer is undefined for other types. Currently, the behaviour is the same as if the value was first converted to boolean. However, do not rely on this behaviour, as it can change without notice.

PHP: Booleans Syntax

Booleans Syntax:

This is the easiest type. A boolean expresses a truth value. It can be either TRUE or FALSE.
The boolean type was introduced in PHP 4.


To specify a boolean literal, use either the keyword TRUE or FALSE. Both are case-insensitive.

$foo = True; // assign the value TRUE to $foo

Usually you use some kind of operator which returns a boolean value, and then pass it on to a control structure.

// == 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 type
if ($show_separators) {
   echo "<hr>\n";

Converting to boolean

To explicitly convert a value to boolean, use either the (bool) or the (boolean) cast. However, in most cases you do not need to use the cast, since a value will be automatically converted if an operator, function or control structure requires a boolean argument.
See also Type Juggling.
When converting to boolean, the following values are considered FALSE:
Every other value is considered TRUE (including any resource).

-1 is considered TRUE, like any other non-zero (whether negative or positive) number!

echo gettype((bool) "");        // bool(false)
echo gettype((bool) 1);         // bool(true)
echo gettype((bool) -2);        // bool(true)
echo gettype((bool) "foo");     // bool(true)
echo gettype((bool) 2.3e5);     // bool(true)
echo gettype((bool) array(12)); // bool(true)
echo gettype((bool) array());   // bool(false)

Dealing with PHP Forms

PHP: Dealing with Forms:

One of the most powerful features of PHP is the way it handles HTML forms. The basic concept that is important to understand is that any form element in a form will automatically be available to your PHP scripts. Please read the manual section on Variables from outside of PHP for more information and examples on using forms with PHP. Here is an example HTML form:

Example 2.6. A simple HTML form

<form action="action.php" method="POST">
Your name: <input type="text" name="name" />
Your age: <input type="text" name="age" />
<input type="submit">

There is nothing special about this form. It is a straight HTML form with no special tags of any kind. When the user fills in this form and hits the submit button, the action.php page is called. In this file you would have something like this:

Example 2.7. Printing data from our form

Hi <?php echo $_POST["name"]; ?>.
You are <?php echo $_POST["age"]; ?> years old.
A sample output of this script may be:

Hi Joe.
You are 22 years old.
It should be obvious what this does. There is nothing more to it. The $_POST["name"] and $_POST["age"] variables are automatically set for you by PHP. Earlier we used the $_SERVER autoglobal, now above we just introduced the $_POST autoglobal which contains all POST data. Notice how the method of our form is POST. If we used the method GET then our form information would live in the $_GET autoglobal instead. You may also use the $_REQUEST autoglobal, if you do not care about the source of your request data. It contains the merged information of GET, POST and COOKIE data. Also see the import_request_variables() function.

User contributed notes:

RobertMaas at YahooGroups dot Com
Regarding debate over GET and POST method: One disadvantage of the POST method is that you can't bookmark it in a URL. So if you want ot make a URL that bookmarks both the WebPage and some form contents, you have to use the GET method, i.e. webpage?formcontents. Warning, the Apache server logs the complete URL including formcontents in a file that anyone can read, so be sure never to include a password in the form in GET method, regardless of whether bookmarked or onetime. For example, my CGI site has a login form, and I have a bookmark for specifying my own (rather long) e-mail address, but do *not* include my password in that bookmark, rather I click on the link and get the login form with my e-mail address already filled in but I still have to type my password, and of course it's a POST instead of GET form when I then submit it with password.
(Cliki complained it was too long so I had to split it.)

pamela at alaskapam dot com
Using two pages for the examples created the output from the first page (Example 2-6. A simple HTML form) on the second page (Example 2-7. Printing data from our form). Then I combined both examples on the action.php page.   When I refreshed the page, I was asked to resend the information which showed the previous entries in the form.  Inputting a new name and age, then submitting query resulted in the form showing the new data.  
I preferred the two-page way of handling this tutorial example.

JohnD717 at hotmail dot com
GET and POST methods: The Get and Post methods in a form is the way the information is passed to the processing script. In PHP these are simply put into $_GET['<name>'] or $_POST['<name>'] however in other languages, like perl/cgi, it is handled differently. if you are writing a generic form for any processor, i recommend post. It is not only easier in languages that handle them differently, but in PHP, POST is the assumed method by more script writers. Also, in PHP, $_GET is used for the query string as well, and you don’t want to end up having duplicate names in the query string and the form.

Useful PHP Examples

Let us do something more useful now. We are going to check what sort of browser the visitor is using. For that, we check the user agent string the browser sends as part of the HTTP request. This information is stored in a variable. Variables always start with a dollar-sign in PHP. The variable we are interested in right now is $_SERVER["HTTP_USER_AGENT"].
$_SERVER is a special reserved PHP variable that contains all web server information. It is known as an autoglobal (or superglobal). See the related manual page on autoglobals for more information. These special variables were introduced in PHP » 4.1.0. Before this time, we used the older $HTTP_*_VARS arrays instead, such as $HTTP_SERVER_VARS. Although deprecated, these older variables still exist. (See also the note on old code.)
To display this variable, you can simply do:
Example 2.2. Printing a variable (Array element)
<?php echo $_SERVER["HTTP_USER_AGENT"]; ?>
A sample output of this script may be:
Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)
There are many types of variables available in PHP. In the above example we printed an Array element. Arrays can be very useful.
$_SERVER is just one variable that is automatically made available to you by PHP. A list can be seen in the Reserved Variables section of the manual or you can get a complete list of them by creating a file that looks like this:
Example 2.3. Show all predefined variables with phpinfo()
<?php phpinfo(); ?>
When you load up this file in your browser, you will see a page full of information about PHP along with a list of all the variables available to you.
You can put multiple PHP statements inside a PHP tag and create little blocks of code that do more than just a single echo. For example, if you want to check for Internet Explorer you can do this:
Example 2.4. Example using control structures and functions
if (strpos($_SERVER["HTTP_USER_AGENT"], "MSIE") !== false) {
   echo "You are using Internet Explorer<br />";
A sample output of this script may be:
You are using Internet Explorer<br />
Here we introduce a couple of new concepts. We have an if statement. If you are familiar with the basic syntax used by the C language, this should look logical to you. Otherwise, you should probably pick up any introductory PHP book and read the first couple of chapters, or read the Language Reference part of the manual. You can find a list of PHP books at »
The second concept we introduced was the strpos() function call. strpos() is a function built into PHP which searches a string for another string. In this case we are looking for "MSIE" (so-called needle) inside $_SERVER["HTTP_USER_AGENT"] (so-called haystack). If the needle is found inside the haystack, the function returns the position of the needle relative to the start of the haystack. Otherwise, it returns FALSE. If it does not return FALSE, the if expression evaluates to TRUE and the code within its {braces} is executed. Otherwise, the code is not run. Feel free to create similar examples, with if, else, and other functions such as strtoupper() and strlen(). Each related manual page contains examples too. If you are unsure how to use functions, you will want to read both the manual page on how to read a function definition and the section about PHP functions.
We can take this a step further and show how you can jump in and out of PHP mode even in the middle of a PHP block:
Example 2.5. Mixing both HTML and PHP modes
if (strpos($_SERVER["HTTP_USER_AGENT"], "MSIE") !== false) {
<h3>strpos must have returned non-false</h3>
<center><b>You are using Internet Explorer</b></center>
} else {
<h3>strpos must have returned false</h3>
<center><b>You are not using Internet Explorer</b></center>
A sample output of this script may be:
<h3>strpos must have returned non-false</h3>
<center><b>You are using Internet Explorer</b></center>
Instead of using a PHP echo statement to output something, we jumped out of PHP mode and just sent straight HTML. The important and powerful point to note here is that the logical flow of the script remains intact. Only one of the HTML blocks will end up getting sent to the viewer depending on the result of strpos(). In other words, it depends on whether the string MSIE was found or not.
User contributed notes:

It wasn't immediately obvious to me what would happen if I jumped from PHP to HTML and back within a function definition. But of course it does the "right thing":
function foo () {
 echo "Enter foo...";
?>Some HTML inside foo...<?
 echo "Leave foo.";
 <? foo(); ?>
Enter foo...Some HTML inside foo...Leave foo.