PHP Basic Part-1 (Comments, Data types, Variable, Constants and Operators)

Print Friendly

What is PHP?

PHP is a programming language that you can use to write Web applications. A Web application can be anything from a simple “contact us” form through to a fully-fledged blogging system, online store, or forum system.

PHP is a server-side language

PHP is known as a server-side programming language. This means that it runs on the Web server. Most Web programming languages are server-side, but some, such as JavaScript, are client-side, which means they run on the Web browser.

Server-side languages give you more flexibility as they can do many things that are hard to do with JavaScript — for example, working with files and databases, or manipulating images. That said, JavaScript is coming along in leaps and bounds these days (as these examples show).

Server-side code is also potentially more secure than JavaScript code. Since JavaScript code is sent to the Web browser it’s easy for a visitor to view and edit the code. Server-side code, on the other hand, remains on the Web server and isn’t accessible to visitors to the site.

PHP is open source

The PHP engine — that is, the code that sits on the Web server and runs PHP scripts — is open source, which means anyone can access and work on the engine’s source code. This helps to ensure that PHP will be around for a long time to come.

PHP is free to download and use, which is one reason why it is so popular among Web hosting companies. You’ll find that the vast majority of Web hosting accounts supports PHP.

PHP is geared towards the Web

While many programming languages can be used to build Web applications, PHP is one of the few languages specifically designed for the Web. To this end, it includes a lot of useful Web-related features out of the box, such as:

  • Easy ways to read and handle Web forms and cookies
  • Functions for creating and manipulating graphics
  • The ability to talk to popular databases such as MySQL, and
  • Functions for working with HTML.

You can mix PHP code with HTML code

One nice feature of PHP is that you can insert chunks of PHP code into an HTML page. You surround the PHP chunks with special symbols. When the Web server retrieves the page, any PHP chunks are run by the PHP engine, while the other parts of the page are sent as they are to the browser.

This feature makes it easy to add interactivity to otherwise plain Web pages — great for contact forms and the like.

Uses of PHP

You can use PHP to write practically any type of Web application or script. Common PHP applications include:

In addition, many popular websites, including Yahoo!, Wikipedia, Facebook, and Digg, use PHP code extensively.

Alternatives to PHP

If you don’t fancy using PHP then there are many similar languages available. Some common server-side languages include:

Writing Your First PHP Script

What you’ll need

In order to start writing PHP scripts, you need access to a Web server running PHP. Your main options are:

  • Run PHP on your own computer: The easiest way to do this is to install a complete package like XAMPP. This contains the Apache Web server, along with PHP and the MySQL database engine, in one easy-to-install package. XAMPP is available for Windows, Mac OS X, and Linux. (A popular alternative on Windows is WampServer.)
  • IDE – Integrated Development Environment
    • Adobe Dreameweaver
    • Notepad++
    • Zend Development Studio
    • PHP Eclipse

Your first script

Here’s the PHP script that you’re going to create:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>My first PHP script</title>
</head>
<body>
<p><?php echo "Hello, world!"; ?></p>
</body>
</html>

As you can see, most of this script is plain XHTML. The PHP code is inside the <?php and ?> tags:


<p><?php echo "Hello, world!"; ?></p>

The <?php and ?> tags tell the Web server to treat everything inside the tags as PHP code to run. (Everything outside these tags is sent straight to the browser as-is.)

This line of code is very simple. It uses a built-in function, echo, to display some text (“Hello, world!”) in the Web page. PHP contains hundreds of functions that you can use to write feature-rich applications.

Notice the semicolon (;) after the PHP code — you need to put a semicolon after each line of code in your PHP scripts.

Note: The semicolon is optional if you’re only writing one line of code, as in this example.

Which of the following tags are acceptable ways to begin a PHP Code block?

  1. <SCRIPT LANGUAGE=”php”>
  2. <!
  3. <%
  4. <?php
  5. <?

Testing the script

Now you’re ready to run your script. To do this, open a Web browser, type the script’s URL into the browser’s address bar, and press Enter. If you’re running the Web server on your own computer then the URL will probably be:

http://localhost/hello.php

If, on the other hand, you’re running the script on a Web hosting account then you need to use something like:

http://www.example.com/hello.php

If all goes well then you should see a page similar to this:

PHP Comments

Like most languages, PHP lets you add comments to your code. Comments are chunks of text that are ignored when the code is run by the PHP engine, but which are useful to programmers who need to read the code.

Now we learn how to create PHP comments, and look at some good commenting practices, including how to write and format comments effectively. You also find out how to use comments to “comment out” chunks of PHP code.

Creating a PHP comment

There are 2 basic types of PHP comments:

  • A single-line comment. This is a short comment within a single line of code.
  • A multi-line comment. This is a longer comment that can stretch over many lines.

Writing single-line comments

To write a single-line comment, place either // (2 slashes) or a # (hash) before the comment:


<?php

// Here's a single-line PHP comment.
# Here's another single-line PHP comment.

?>

Note: The first comment style tends to be more popular with PHP programmers, but both styles are perfectly valid.

You can write single-line comments on their own — as just shown — or you can place a comment at

the end of a line of code:


<?php

$widgetsLeft--; // Sold another widget!

?>

Note: Everything from the comment symbol (// or #) to the end of the line is treated as a comment by the PHP engine, and is ignored.

Writing multi-line comments

To write a multi-line comment, start the comment with /* (a slash followed by an asterisk) and end the comment with */ (an asterisk followed by a slash). Here’s an example:


<?php

/*
Here's a long PHP comment spread over
many lines.

You can format a multi-line comment
any way you like.
*/

?>

Be careful: You can’t nest multi-line comments in PHP. The following code won’t work:


<?php
/*
Here's the start of the outer comment.
/* Here's the inner comment. */
Here's the end of the outer comment.
*/

?>

This mistake is easy to make when commenting out PHP code, as described in a moment.

Good PHP commenting practice

It’s important to comment your PHP code. Code has a habit of making sense at the time you write it, then looking like a mess in 3 months’ time! If you add comments at the time you write your code then you will find that your code is a lot more readable when you (or another developer) return to it later.

A comment should explain what a chunk of code does, or is intended to do. Here are some good examples:


<?php
if ( $widget->stockLeft == 0 ) $widget->delete(); // Remove the widget if it's sold out

// Show only recent articles
for ( $i=0; $i < count( $articles ); $i++ ) {
if ( time() - $articles[$i]->pubDate < (86400 * 7) ) $articles[$i]->displayTitle();
}

?>

Formatting comments

It’s good to format your comments to make them easy to read. The following PHP comments are hard to read due to bad formatting:


<?php

// Retrieve all widgets
$widgets = Widget::getAll();
/*Update all the widgets in the database,
changing each widget's quantity*/
for ( $i=0; $i < count( $widgets ); $i++ ) {
$widgets[$i]->quantity += $widgets[$i]->getNewStock(); //Set the quantity
$widgets[$i]->update(); //Update the widget
}

?>

These comments, on the other hand, are much easier on the eye:


<?php

// Retrieve all widgets
$widgets = Widget::getAll();

/*
Update all the widgets in the database,
changing each widget's quantity
*/

for ( $i=0; $i < count( $widgets ); $i++ ) {
$widgets[$i]->quantity += $widgets[$i]->getNewStock();   // Set the quantity
$widgets[$i]->update();                                  // Update the widget
}

?>

Commenting out PHP code

You can use PHP comments to “comment out” (temporarily disable) chunks of code. This can be useful when debugging your PHP scripts:


<?php

/*
if ( $widget->stockLeft == 0 ) $widget->delete(); // Remove the widget if it's sold out

// Show only recent articles
for ( $i=0; $i < count( $articles ); $i++ ) {
if ( time() - $articles[$i]->pubDate < (86400 * 7) ) $articles[$i]->displayTitle();
}
*/

?>

However, be careful when commenting out PHP code containing multi-line comments. Since you can’t nest multi-line comments in PHP, the following won’t work:


<?php
/*
/*
Update all the widgets in the database,
changing each widget's quantity
*/

for ( $i=0; $i < count( $widgets ); $i++ ) {
$widgets[$i]->quantity += $widgets[$i]->getNewStock();   // Set the quantity
$widgets[$i]->update();                                  // Update the widget
}
*/

?>

PHP Data Types

Most PHP scripts deal with data in one form or another, usually stored in variables. PHP can work with different types of data. For example, a whole number is said to have an integer data type, while a string of text has a string data type.

Now we explore PHP’s data types; look at loose typing; learn how to discover the type of a given value; and see how to change data types.

PHP’s scalar data types

Scalar data is data that only contains a single value. As of version 6, PHP features 6 scalar data types:

Type

Description

Example values

integer  A whole number (32 bit) 7, -23
float  A floating point number (32 bits with fraction) 7.68, -23.45
string  A sequence of characters "Hello", "abc123@#$"
unicode  A sequence of Unicode characters "Hello", "abc123@#$"
binary  A sequence of binary (non-Unicode) characters "Hello", "abc123@#$"
boolean  Either true or false true, false

The Unicode and binary types were added in PHP 6. Earlier PHP versions just have a string type.

PHP’s compound data types

Compound data can contain multiple values. PHP has 2 compound data types:

Array              Can hold multiple values indexed by numbers or strings

Object             Can hold multiple values (properties), and can also contain methods (functions) for working on properties

An array or object can contain multiple values, all accessed via one variable name. What’s more, those values can themselves be other arrays or objects. This allows you to create quite complex collections of data.

Loose typing in PHP

Some languages, such as Java, are strongly typed: once you’ve created a variable, you can’t change the type of data stored in it. PHP, in contrast, is loosely typed: you can change a variable’s data type at any time.

In the following PHP example, $x starts off by holding integer data (3). The next line appends the string “hello” to the data using the concatenation operator, which changes $x‘s value to “3hello” (a string data type). Finally, 5.67 is assigned to $x, changing its data type to a float:


<?php

$x = 3;
$x .= "hello";
$x = 5.67;

?>

Finding out the data type of a value

You can check a value’s data type using one of the following PHP functions:

is_int( value )      Returns true if value is an integer, false otherwise

is_float( value )    Returns true if value is a float, false otherwise

is_string( value )   Returns true if value is a string, false otherwise

is_unicode( valueReturns true if value is a Unicode string, false otherwise

is_binary( value )   Returns true if value is a binary string, false otherwise

is_bool( value )     Returns true if value is a Boolean, false otherwise

is_array( value )    Returns true if value is an array, false otherwise

is_object( value )   Returns true if value is an object, false otherwise

is_null( value )     Returns true if value is null, false otherwise


Note: is_unicode() and is_binary() are only available in PHP 6 and later.

For example, the following code displays 1 (true):


<?php
$x = 3.14;
echo is_float( $x );
?>

Changing data types with settype()

As you’ve already seen, you can change a variable’s data type simply by assigning a new value of a different type to the variable. However, sometimes it’s a good idea to explicitly set the type of the data held by a variable. For example, if you’re handing data entered by a visitor, or passing data to another program, then it’s good to ensure that the data is of the correct type.

PHP has a function called settype() that converts a variable’s value from one data type to another:


<?php

$x = 3.14;
settype( $x, "integer" );
?>

In the above example, $x‘s data type is changed from float to integer (with the result that $x ends up containing the value 3).

Be careful when changing data types, since you may end up losing information — for example, when changing a float (3.14) to an integer (3).

Changing data types with casting

If you just want to change a value’s type at the time you use the value, then you can use casting. This merely changes the type of the value that is to be used; the original variable remains untouched.

To cast a value, place the data type in parentheses before the value at the time you use it:

$x = 3.14;
echo (integer) $x;

The above code displays 3 (3.14 cast to an integer). However, note that $x still contains the value 3.14 after the cast operation.

Note: You can, if you prefer, use (int) instead of (integer), and (bool) instead of (boolean).

Strings

Syntax

A string literal can be specified in four different ways:

  • Single quoted
  • Double quoted
  • Heredoc syntax
  • Nowdoc syntax (since PHP 5.3.0)

Single quoted

The simplest way to specify a string is to enclose it in single quotes (the character ).

To specify a literal single quote, escape it with a backslash (\). To specify a literal backslash, double it (\\).


<?php
echo 'this is a simple string<br>';
// Outputs: Arnold once said: "I'll be back"
echo 'Arnold once said: "I\'ll be back"<br>';
// Outputs: You deleted C:\*.*?
echo 'You deleted C:\\*.*?<br>';
// Outputs: You deleted C:\*.*?
echo 'You deleted C:\*.*?<br>';
// Outputs: This will not expand: \n a newline
echo 'This will not expand: \n a newline<br>';
// Outputs: Variables do not $expand $either
$expand="Expanded";
$either="Not Expanded";
echo 'Variables do not $expand $either';
?>

Double quoted

If the string is enclosed in double-quotes (“), PHP will interpret more escape sequences for special characters:


<?php
echo "this is a simple string<br>";
// Outputs: Arnold once said: "I'll be back"
echo "Arnold once said: I\'ll be back<br>";
// Outputs: You deleted C:\*.*?
echo "You deleted C:\\*.*?<br>";
// Outputs: You deleted C:\*.*?
echo "You deleted C:\*.*?<br>";
// Outputs: This will not expand: \n a newline
echo "This will not expand: \n a newline<br>";
// Outputs: Variables do not $expand $either
$expand="Expanded";
$either="Not either";
echo "Variables do not $expand $either";
?>

]

Heredoc

A third way to delimit strings is the heredoc syntax: <<<. After this operator, an identifier is provided, then a newline. The string itself follows, and then the same identifier again to close the quotation.

The closing identifier must begin in the first column of the line. Also, the identifier must follow the same naming rules as any other label in PHP: it must contain only alphanumeric characters and underscores, and must start with a non-digit character or underscore.

Example #1 without quotes in Heredoc


<?php
$name="Masud Alam";
$email="[email protected]";
$address="Dhaka,Bangladesh";
$mob_no="01722817591";
$str = <<<HEREDOC
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<table width="200" border="1">
<tr>
<td>Name:</td>
<td>$name;</td>
</tr>
<tr>
<td>Email:</td>
<td>$email</td>
</tr>
<tr>
<td>Address:</td>
<td>$address</td>
</tr>
<tr>
<td>Mobile No:</td>
<td>$mob_no</td>
</tr>
</table>
</body>
</html>
HEREDOC;
echo $str;
?>

Example #2 with double quotes in Heredoc


<?php

<?php
echo <<<"FOOBAR"
Hello World!
FOOBAR;
?>

?>

Nowdoc

Nowdocs are to single-quoted strings what heredocs are to double-quoted strings. A nowdoc is specified similarly to a heredoc, but no parsing is done inside a nowdoc.

Example #1 with single quotes in NowDoc


<?php
$str = 'This is a test.';
echo <<< 'FOOBAR '
Hello World!
<br>
$str;
FOOBAR;
?>

PHP Variables

Like most programming languages, PHP lets you create variables in your scripts. A variable is a storage container that holds a value. This value can change as the script runs. You can:

  • Assign any value you like to a variable
  • Access the value stored in a variable, and
  • Change a variable’s value at any time.

Variables are useful because they let you write flexible scripts. For example, a script that can only add 3 and 4 together isn’t very useful. A script that can add any two values together, though, is much more flexible.

Creating a variable

To create a new variable in PHP, you can just write the variable’s name:

$myVariable;

Notice the dollar ($) symbol before the variable name. All PHP variables have a dollar symbol in front.

This is known as declaring a variable. It’s also a good idea to give the variable an initial value at the time you declare it — this is known as initializing the variable:

$myVariable = 23;

Note: If you don’t initialize a new variable then it takes on a value of null.

Changing a variable’s value

You’ve just seen how to assign a value to a variable: you simply write the variable name, followed by an equals sign, followed by the value you want to assign.

To change a variable’s value, simply assign the new value:


<?php

$myVariable = 23;
$myVariable = 45;
$myVariable = "hello";
?>

The first line of code creates a new variable with a numeric value of 23, while the second line changes the variable’s value to 45. The third line changes the value again — this time to a string of text, “hello”.

PHP is a loosely-typed language, which means you can change the type of data that a variable holds whenever you like. In the above example, $myVariable starts off holding a number, and finishes by holding a string of text.

Using a variable’s value

To use the value of a variable in your script, simply write the variable’s name. For example, to display the value of $myVariable you’d use:


<?php

echo $myVariable;

?>

To add the values of two variables $x and $y together and display the result, you could write:


<?php

echo $x + $y;

?>

Variable names in PHP

Before leaving the topic of PHP variables, it’s worth taking a look at how to name variables. All PHP variable names have to follow these rules:

  • They start with a $ (dollar) symbol.
  • The first character after the dollar must be either a letter or a _ (underscore) symbol.
  • The other characters may be letters, numbers, and/or underscores.

Variable names can be as long as you like, but it’s a good idea to keep them relatively short (otherwise they can get quite unwieldy). It’s also good to use meaningful variable names — for example, $numWidgets is much more useful than $nw.

PHP variable names are case-sensitive, which means that $myVariable and $MyVariable refer to different variables.

Which of the following are valid PHP variables?

@$foo
&$variable
${0}
${1}
${0x0}
${0y0}
${030}
$variable
$0x0
${0*0}
${0+0}
${0-0}
${0/0}
${0%0}

Variable scope

The scope of a variable is the context within which it is defined. For the most part all PHP variables only have a single scope. This single scope spans included and required files as well. For example:

b.inc file


<?php
$a=2;
?>
<?php
$a = 1;
include 'b.inc';
echo $a;
?>

Here the $a variable will be available within the included b.inc script

Within user-defined functions a local function scope is introduced. Any variable used inside a function is by default limited to the local function scope. For example:


<?php
$a = 1; /* global scope */

function test()
{
echo $a; /* reference to local scope variable */
}

test();
?>

This script will not produce any output because the echo statement refers to a local version of the $a variable, and it has not been assigned a value within this scope. You may notice that this is a little bit different from the C language in that global variables in C are automatically available to functions unless specifically overridden by a local definition. This can cause some problems in that people may inadvertently change a global variable. In PHP global variables must be declared global inside a function if they are going to be used in that function.

The global keyword

First, an example use of global:

Example #1 Using global


<?php
$a = 1;
$b = 2;

function Sum()
{
global $a, $b;

$b = $a + $b;
}

Sum();
echo $b;
?>

The above script will output 3. By declaring $a and $b global within the function, all references to either variable will refer to the global version. There is no limit to the number of global variables that can be manipulated by a function.

A second way to access variables from the global scope is to use the special PHP-defined $GLOBALS array. The previous example can be rewritten as:

 

Example #2 Using $GLOBALS instead of global


<?php
$a = 1;
$b = 2;

function Sum()
{
$GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];
}

Sum();
echo $b;
?>

Using static variables

Another important feature of variable scoping is the static variable. A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope. Consider the following example:


<?php
function test()
{
$a = 0;
echo $a;
$a++;
}
test(); // Output will be 0
test();// Output will be 0
test();// Output will be 0
?>

This function is quite useless since every time it is called it sets $a to 0 and prints 0. The $a++ which increments the variable serves no purpose since as soon as the function exits the $a variable disappears. To make a useful counting function which will not lose track of the current count, the $a variable is declared static:

<?php
function test()
{
    static $a = 0;
    echo $a;
    $a++;
}
test(); // output should 0
test(); // output should 1
test(); //output should 2
?>

Now, $a is initialized only in first call of function and every time the test() function is called it will print the value of $a and increment it.

Variable variables

Sometimes it is convenient to be able to have variable variable names. That is, a variable name which can be set and used dynamically. A normal variable is set with a statement such as:


<?php
$a = 'hello';
?>

A variable variable takes the value of a variable and treats that as the name of a variable. In the above example, hello, can be used as the name of a variable by using two dollar signs. i.e.


<?php
$a = 'hello';
?>

At this point two variables have been defined and stored in the PHP symbol tree: $a with contents “hello” and $hello with contents “world”. Therefore, this statement:


<?php
$a = 'hello';
$$a = 'world';
echo "$a ${$a}"; // Hello World
?>

Produces the exact same output as:


<?php
$a = 'hello';
$$a = 'world';
echo "$a $hello";
?>

PHP Superglobals

PHP provides a special set of predefined global arrays containing various useful nuggets of information. These arrays are known as superglobals because they’re accessible from anywhere in your script — including inside functions — and you don’t need to declare them as global using the global keyword.

Here’s a full list of the superglobals available in PHP, as of version 5.3:

$GLOBALS    Contains a list of all global variables in the script (excluding superglobals)

$_GET       Holds a list of all form fields sent by the browser using the GET request

$_POST      Holds a list of all form fields sent by the browser using the POST request

$_COOKIE    holds a list of all cookies sent by the browser

$_REQUEST   Contains all the keys and values in the $_GET, $_POST and $_COOKIE arrays combined

$_FILES     holds a list of any files uploaded by the browser

$_SESSION   allows you to store and retrieve persistent session variables for the current browser

$_SERVER    Holds server environment info such as the filename of the running script, and the IP address of the browser.

$_ENV       contains a list of environment variables passed to PHP. These can include variables provided by the shell, as well as CGI variables.

For example, we can use the $_GET superglobal to retrieve a value included in the query string of the script’s URL, and display the value in the page:


<?php

$yourName = $_GET['yourName'];
echo "Hello, $yourName!";

?>

If you run the above script using a URL along the lines of  http://www.example.com/script.php?yourName=Fred    then the script displays:

Hello, Fred!

PHP Constants

PHP constants explained

Like variables, PHP constants can store values. However, once a constant has been created, its value cannot be changed while the script runs.

Constants are useful for storing data that doesn’t (and shouldn’t) change while the script is running. Common examples of such data include configuration settings (such as database usernames and passwords) and fixed strings of text to display to visitors (such as “Please login to continue”).

Constants are also often used to represent integer values with special meanings in a particular context, such as error codes and flags.

How to create a constant

PHP constant names follow the same rules as PHP variable names. The only difference is that constant names don’t start with a $ (dollar) symbol, while variable names do.

PHP constant names are case-sensitive. Usually, constant names use all-uppercase letters, with underscores to separate words within the name.

To create a PHP constant, use the following syntax:


define( "CONSTANT_NAME", constant_value );

CONSTANT_NAME” is a string holding the name of the constant to create, while constant_value is the value that the constant will hold. Here are a couple of examples:

<?php
define( "HELLO", "Hello, world!" );
define( "WIDGET_PRICE", 29.99 );

?>

The first line of code creates a PHP constant called HELLO with a string value of “Hello, world!”, while the second line creates a constant called WIDGET_PRICE with a numeric value of 29.99.

PHP constants can only hold scalar values — these include numbers, strings of text, and boolean values. They can’t hold arrays or objects, like variables can.

You can only define a constant once within a script. If you try to redefine a constant, the PHP engine generates an error.

Using constants in PHP

You access a PHP constant in exactly the same way as you use a variable. To use a constant’s value, simply write the constant name. The following example displays the values of the HELLO and WIDGET_PRICE constants:


<?php
echo HELLO;
echo WIDGET_PRICE;
?>

Predefined constants

PHP features a large number of built-in, predefined constants holding various useful values. Some of these are always available, while other constants become available when certain PHP extensions are enabled. For example, the PHP constant M_PIholds the mathematical constant Pi. The following code displays this value:


<?php
echo M_PI;
?>

Another useful predefined constant is PHP_VERSION, which holds the current version of the running PHP engine:


<?php
echo PHP_VERSION;

?>

The PHP website has a list of built-in predefined constants.

PHP Operators

PHP variables are great for storing values in your script, but they’re not much use on their own. To manipulate variable values and get useful results, you need to use operators.

What are PHP operators?

PHP operators let you combine values together to produce new values. For example, to add two numbers together to produce a new value, you use the +(addition) operator. The following PHP code displays the number 5:

<?php
echo 2 + 3;
?>

The value or values that an operator works on are known as operands. In this tutorial you look at common PHP operators, and you also explore the concept of operator precedence.

Common PHP operators

There are many PHP operators, but this article concentrates on the ones you’re likely to use most often. These can be broken down into the following operator types:

Arithmetic Carry out arithmetic operations such as addition and multiplication
Assignment Assign values to variables
Comparison Compare 2 values
Bitwise Operators Allow evaluation and manipulation of specific bits within an integer.
Increment/decrement Increase or decrease the value of a variable
Logical Perform Boolean logic
String Join strings together
Error Control Operators the at sign (@). When prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored.
Ternary Operator A ternary operator can be used as a slightly faster, cleaner way to write simple if/else statements.

The following sections explore each of these operator types.

Arithmetic operators

PHP features 5 arithmetic operators:

Symbol Name Example Result
+ addition echo 7 + 5 12
- subtraction echo 7 - 5 2
* multiplication echo 7 * 5 35
/ division echo 7 / 5 1.4
% modulus echo 7 % 5 2

The first four operators should be self-explanatory. %(modulus) is simply the remainder of dividing the two operands. In this case, 7 divided by 5 is 1 with a remainder of 2, so the result of the modulus operation is 2.

Assignment operators

The basic assignment operator is =(an equals sign). This is used to assign a value to a variable

<?php
$myVariable = 23;

?>

The value to assign doesn’t have to be a literal value — it can be any expression. In the following example, $myVariabletakes on the value 12:


<?php
$firstNum = 7;
$secondNum = 5;
$myVariable = $firstNum + $secondNum;

?>

As with most PHP operators, the assignment operator doesn’t just carry out the operation — it also produces a resulting value, which in this case is the value that was assigned. This allows you to write code such as:


<?php
$firstNum = 7;
$secondNum = 5;
$anotherVariable = $myVariable = $firstNum + $secondNum;
?>

In this example, $myVariable is assigned the value 12 (the result of $firstNum + $secondNum). This assignment operation also produces a result of 12, which is then assigned to $anotherVariable. So both $myVariable and $anotherVariable end up storing the value 12. You can also combine many operators with the assignment operator — these are known as combined assignment operators. For example, say you wanted to add 3 to the value of $myVariable. You could write:


<?php
$myVariable = $myVariable + 3;
?>

However, with a combined assignment operator, you can simply write:


<?php
$myVariable += 3;
?>

Comparison operators

PHP’s comparison operators compare 2 values, producing a Boolean result of true if the comparison succeeded, or false if it failed. You often use comparison operators with statements such as if and while. PHP supports the following 8 comparison operators:

Symbol Name Usage Result
== equal to a == b  true if a equals b, otherwise false
!= not equal to a != b  true if a does not equal b, otherwise false
=== identical to a === b  true if a equals b and they are of the same type, otherwise false
!== not identical to a !== b  true if a does not equal b or they are not of the same type, otherwise false
< less than a < b  true if a is less than b, otherwise false
> greater than a > b  true if a is greater than b, otherwise false
<= less than or equal to a <= b  true if a is less than or equal to b, otherwise false
>= greater than or equal to a >= b  true if a is greater than or equal to b, otherwise false

PHP displays the value true as the number 1, and the value false as an empty string. So the following lines of code each display 1 because the comparison operations evaluate to true:


<?php
echo ( 7 == 7 );
echo ( 3 < 5 );
echo ( 6 === 6 );

?>

The following lines of code each display nothing at all (an empty string) because the comparison operations evaluate to false:


<?php
echo ( 7 != 7 );
echo ( 3 > 5 );
echo ( 6 === "6" );

?>

(The last comparison evaluates to false because 6 (an integer) and “6” (a string) are not of the same type, even though their values are essentially equal.)

Bitwise Operator

The bitwise operators and binary math in general have always been a mystery to me. If not for studying for the zend certification I still would probably not care to learn them 🙂 However here I am and I finally got down the mystery of bits and bytes. What this tutorial will cover: 1. What are bits and bytes and binary math? 2. PHP’s Bitwise Operators 3. A simple usecase for why you would want to use bitwise operators

What is Bits, Bytes, and Binary Math BINARY MATH INTRODUCTION

The bitwise operators utilize something called Binary Math. If you already know binary math, skip ahead. Binary math is a BASE 2 numbering system, where as our normal everyday numbering system is a BASE 10 system.

Think back to elementary school where we learned numbers this way… Think of the number 4768. That’s a normal everyday decimal number.

If you write that out full its 4 THOUSAND, 7 HUNDRED, 6 TENS, 8 ONES or (4 * 103) + (7 * 102) + (6 * 101) + (8 * 100) = 4768 The BASE 2 system has the same concept however it goes by 2’s instead of 10s. So you can only have a value of 0 or 1.

Lets look at a binary number

00101101 = (0 * 27) + (0 * 26) + (1 * 25) + (0 * 24) + (1 * 23) + (1 * 22) + (0 * 21) + (1 * 20) = 32 + 8 + 4 + 1 = 45

Wow thats alot of math. Lets break it down piece by piece starting with the first parentheses. (0 * 27) which means 0 TIMES 2 to the POWER of 7 or 0 * ( 2 * 2 * 2 * 2 * 2 * 2 * 2) which basically comes out to 0 * 128 which equals 0 (0 times anything is 0) so going down our binary number we can see it calculates like this:

0 – (0 * 128) = 0 0 – (0 * 64) = 0 1 – (1 * 32) = 32 0 – (0 * 16) = 0 1 – (1 * 8) = 8 1 – (1 * 4) = 4 0 – (0 * 2) = 0 1 – (1 * 1) = 1

so add those all up together 32 + 8 + 4 + 1 and you get 45 What is a bit? A bit is a representation of 1 or 0.

Basically OFF and ON. Why do computers use such simple math? Well computers process with electric current so if the current is over a certain level the computer considers that to mean ON or 1 and if it is under that level it is set to OFF or 0.

What is a byte? A byte is made up of 8 bits and the highest value of a byte is 255, which would mean every bit is set.

We will look at why a byte’s maximum value is 255 in just a second. What does a byte look like?

1 Byte ( 8 bits )
Place Value 128 64 32 16 8 4 2 1

That is a representation of 1 Byte. The “Place Value” column represents the math we did doing 2 to the power of 7,6,5,4,3,2,1,0 So if all bits are set and the value = 255 my byte would look like this

1 Byte ( 8 bits )
Place Value 128 64 32 16 8 4 2 1
1 1 1 1 1 1 1 1 = 255

How do we get 255? Lets take it right to left and add up all those values together

1 + 2 + 4 + 8 + 16 + 32 + 64 + 128 = 255

What would the number 22 look like?

1 Byte ( 8 bits )
Place Value 128 64 32 16 8 4 2 1
0 0 0 1 0 1 1 0 = 22

2 + 4 + 16 = 22

Let’s look at some other examples of decimal to binary, the ones on the end try for yourself.

43 = 00101011 4 = 00000100 230 = ? 65 = ? 31 = ?

PHP’S BITWISE OPERATORS

You can find complete detail on the PHP bitwise operators here: http://www.php.net/manual/en/language.operators.bitwise.phpWhat are going to cover? We’re going to cover the bitwise operators below and see how they work

Example Name Result
$a & $b And Bits that are set in both $a and $b are set.
$a | $b Or Bits that are set in either $a or $b are set.
$a ^ $b Xor Bits that are set in $a or $b but not both are set.
~ $a Not Bits that are set in $a are not set, and vice versa.
$a << $b Shift left Shift the bits of $a $b steps to the left (each step means “multiply by two”)
$a >> $b Shift right Shift the bits of $a $b steps to the right (each step means “divide by two”)

Lets use two variables to get started with the “And” operator &. The & or “And” operator takes two values and returns a decimal version of the binary values the left and right variable share.

So using our tables above we can see that the only bit these two share is in the 8 position so $a & $b = 8.


<?php
$a =9;
$b =10;
echo $a & $b;

?>

This would output the number 36. Why?? Well lets see using our table example again

1 Byte ( 8 bits )
Place Value 128 64 32 16 8 4 2 1
$a 0 0 1 0 0 1 0 0 = 36
$b 0 1 1 0 0 1 1 1 = 103

So you can see the only bits these two share together are the bits 32 and 4 which when added together return 36. This operator is saying “I want to know what bits you both have set in the same column”

Lets move on to the | also known as the “OR” operator.


<?php
$a =9;
$b =10;
echo $a | $b;

?>

This would output the number 11. Why?? Well lets see using our table example

1 Byte ( 8 bits )
Place Value 128 64 32 16 8 4 2 1
$a 0 0 0 0 1 0 0 1 = 9
$b 0 0 0 0 1 0 1 0 = 10

If you notice we have 3 bits set, in the 8, 2, and 1 column.. add those up 8+2+1 and you get 11. It is just saying “I want to know what bits either one of you guys have set”.

Moving on to the ^ operator also known as the “Xor” operator.


<?php
$a =9;
$b =10;
echo $a ^ $b;

?>

 This would output the number 3. Why?? Well lets see using our table example

1 Byte ( 8 bits )
Place Value 128 64 32 16 8 4 2 1
$a 0 0 0 0 1 0 0 1 = 9
$b 0 0 0 0 1 0 1 0 = 10

The XOR operator wants to know “Tell me what bits you both have set but I dont want any bits you share” Notice we have 3 bits set but both $a and $b share the 8 bit, we dont want that one, we just want the 2 bit and the 1 bit that they each have set but don’t share. Soooo 2+1 = 3

OK, here is one that gets tricky the ~ operator also known as the “NOT” operator.


<?php
$a =9;
$b =10;
echo $a & ~$b;

?>

This would output the number 1. Why?? Well lets see using our table example

1 Byte ( 8 bits )
Place Value 128 64 32 16 8 4 2 1
$a 0 0 0 0 1 0 0 1 = 9
$b 0 0 0 0 1 0 1 0 = 10

The NOT operator wants to know what is set in $a but NOT set in $b because we marked $b with the ~operator in front of it.

So looking at our table we can see the only bit set in $a thats not in $b is 1. What happens if we do this…?


<?php
$a =9;
$b =10;
echo ~$a & $b;
?>

We get the value 2, because we want the bits set in $b but NOT set in $a this time, so since they both share the 8 bit, 2 bit is the only one $b has that $a does not.

BIT SHIFTING TIME!!!


<?php
$a =16;
echo $a << 2;
?>

This would output the number 64. Why?? Well lets see using our table example

1 Byte ( 8 bits )
Place Value 128 64 32 16 8 4 2 1
$a – BEFORE! 0 0 0 1 0 0 0 0 = 16
$a – AFTER! 0 1 0 0 0 0 0 0 = 64

How do we get 64? well bit shifting tells PHP to take the variable $a which in our case is 16 and shift if 2 bits which is basically like saying take 16 and multiply it by 2 twice. So 16 X 2 = 32 x 2 = 64

So what useful things can you do with the bitwise operations?

Here is a VERY simple and watered down user permissions system.

This is great if you have many classes of permission for users for example… a user can…read articles write articles edit articles be an local Administrator be a global Administrator So you can setup your permission rules like this in your configuration file


<?php
$read = 1;
$write = 2;
$readwrite = 16;
$local_admin = 32;
$global_admin = 64;

$jim = 96;
$mike = 16;

echo "Is Mike Allowed to edit? he has an access level of 16<BR>";
if($mike & 32)
{
	echo  'YES MIKE CAN EDIT';
} else {
	echo  'NO HE CANNOT';
}

echo "<BR><BR>Is Jim  Allowed to edit? he has an access level of 96<BR>";
if($jim & 32)
{
	echo  'YES JIM CAN EDIT';
} else {
	echo  'NO HE CANNOT';
}

?>

When you run that code you’ll see Is Mike Allowed to edit? he has an access level of 16 NO HE CANNOT Is Jim Allowed to edit? he has an access level of 32 YES JIM CAN EDIT Using the AND operator we can clearly see if Mike has the 32 bit set that is required for this local admin operation, not only is Jim a local admin but he’s also a global admin with the 64 and 32 bit set giving him a 96 permission level. Imagine if you had 20 different levels of access in your application, being able to store all those in a single integer is VERY handy instead of having to do something like if(is_local_admin && is_global_admin && can_edit_articles && can_view_articles) etc…. that could get long, ugly and hard to manage. Thats about all I have time for at the moment, but I hope to add more useful things you can do with bitwise operators in the future.

Increment/decrement operators

These two operators are very simple — they increase or decrease the value of a variable by 1:

Symbol Name Example Result
++ increment $x++ or ++$x Adds 1 to the variable $x
-- decrement $x-- or --$x Subtracts 1 from the variable $x

The increment and decrement operators are handy when looping through a set of data, or when counting in general. If you place the operator after the variable name then the expression’s value is the value of the variable before it was incremented or decremented. For example, the following code displays the number 4, even though $x‘s value is increased to 5:


<?php
$x = 4;
echo $x++;
?>

On the other hand, if you place the operator before the variable name then the expression evaluates to the value of the variable afterit was incremented or decremented. For example, this code displays the number 5:

<?php
$x = 4;
echo ++$x;
?>

Logical operators

PHP’s logical operators combine values using Boolean logic. Each value to be combined is treated as either true or false — for example, 1, true, a non-empty string, and a successful comparison are all considered true, while 0, false, an empty string, and an unsuccessful comparison are all considered false. The true and/or false values are then combined to produce a final result of either true or false. PHP supports 6 logical operators:

Symbol Name Example Result
&& and a && b  true if a and b are true, otherwise false
and and a and b  true if a and b are true, otherwise false
|| or a || b  true if a or b are true, otherwise false
or or a or b  true if a or b are true, otherwise false
xor xor a xor b  true if a or b — but not both — are true, otherwise false
! not !a  true if a is false; false if a is true

Note: and and or carry out the same operations as && and ||; however the former have lower precedence than the latter. Usually you’ll want to use && and ||, rather than and or or. PHP’s logical operators are often used with comparison operatorsto make more complex comparisons.

String operators

The main string operator is the . (dot) operator, which is used to join, or concatenate, two or more strings together. For example, the following code displays “Hello there!”:


<?php
echo "Hello " . "there!";
?>

As with many other operators, you can combine the . operator with the = operator to produce a combined assignment operator (.=). The following code also displays “Hello there!”:


<?php
$a = "Hello";
$a .= " ";
$a .= "there!";
echo $a;

?>

Error Control Operators

PHP supports one error control operator: the at sign (@). When prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored. If the track_errors feature is enabled, any error message generated by the expression will be saved in the variable $php_errormsg. This variable will be overwritten on each error, so check early if you want to use it.


<?php
/* Intentional file error */
$my_file = @file ('non_existent_file') or
die ("Failed opening file: error was '$php_errormsg'");

// this works for any expression, not just functions:
$value = @$cache[$key];
// will not issue a notice if the index $key doesn't exist.

?>

Note: The @-operator works only on expressions. A simple rule of thumb is: if you can take the value of something, you can prepend the @ operator to it. For instance, you can prepend it to variables, function and include() calls, constants, and so forth. You cannot prepend it to function or class definitions, or conditional structures such as if and foreach, and so forth.

Ternary Operators

The PHP ternary operator is a shorthand way of writing an if/else conditional statement. At first, it can be confusing to understand and may not be as easy to read as your standard if/else conditional statement. However, as you continue to use it you will realize that it is very useful when you want to save a few lines as well as tidy up your code. It is called the ternary operator because it takes three operands – a condition, a result for true, and a result for false. The condition is separated from the results by a ‘?’ question mark. The first result which returns if the condition evaluates to true is separated by a ‘:’ colon from the second result which returns if the condition evaluates to false. Your standard if/else conditional statement may look something like this:

if (condition) {
    $variable = true;
} else {
    $variable = false;
}

The same five lines of code above can be written in one line of code using the PHP ternary operator:

$variable = (condition) ? true : false;

A more real world example might look something like this:


<?php
// standard if/else conditional statement
$compiled = true;

if ($compiled) {
$language = 'C';
} else {
$language = 'PHP';
}

// the same statement above using the ternary operator
$language = ($compiled) ? 'C' : 'PHP';

?>

You can also use the ternary operator to echo strings:

<?php
// standard if/else conditional statement
if (condition) {
    echo 'condition is true';
} else {
   echo 'condition is false';
}

// the same statement above using the ternary operator
echo (condition) ? 'condition is true' : 'condition is false';

?>

As you can see, the ternary operator can be very helpful for cleaning up your code. I wouldn’t recommend using it for complex conditional statements but for simple ones it is a great tool.

Operator precedence in PHP

All PHP operators have a precedence, which determines when the operator is applied in an expression. Consider the following expression:

echo 4+5*6;

You could read this expression in one of two ways:
  • Add 5 to 4, then multiply the result by 6 to produce 54
  • Multiply 5 by 6, then add 4 to produce 34
In fact PHP takes the second approach, because the * (multiplication) operator has a higher precedence than the +(addition) operator. PHP first multiplies 5 by 6 to produce 30, then adds 4 to produce 34.

Here's a list of common PHP operators ordered by precedence (highest precedence first):
Operator(s) Description
++ -- increment/decrement
(int) (float) (string) (array) (object) (bool) casting
! logical “not”
* / % arithmetic
+ - . arithmetic and string
< <= > >= <> comparison
== != === !== comparison
&& logical “and”
|| logical “or”
= += -= *= /= .= %= assignment
and logical “and”
xor logical “xor”
or logical “or”
Note:Operators on the same line in the list have the same precedence.

If you want to change the order that operators are applied, use parentheses. The following expression evaluates to 54, not 34:
( 4 + 5 ) * 6

<?php
function test()
{
    static 
$a 0;
    echo 
$a;
    
$a++;
}

test(); // output should 0

test(); // output should 1

test(); //output should 2
?>

Hi, My name is Masud Alam, love to work with Open Source Technologies, living in Dhaka, Bangladesh. I graduated in 2009 with a bachelor’s degree in Engineering from State University Of Bangladesh, I’m also a Certified Engineer on ZEND PHP 5.3, I served my first five years a number of leadership positions at Winux Soft Ltd, SSL Wireless Ltd, CIDA and MAX Group where I worked on ERP software and web development., but now i’m a co-founder and Chief Executive Officer and Managing Director of TechBeeo Software Consultancy Services Ltd. I’m also a Course Instructor of ZCE PHP 5.3 Certification and professional web development course at IBCS-PRIMAX Software (Bangladesh) Limited – a leading Training Institute in the country.
Print Friendly
15 comments on “PHP Basic Part-1 (Comments, Data types, Variable, Constants and Operators)
  1. Example code used in STRING- DOUBLE QUOTED, are misleading for readers. For example,
    // Outputs: Variables do not $expand $either
    $expand=”Expanded”;
    $either=”Not either”;
    echo “Variables do not $expand $either”;

    Thanks

  2. I believe that is among the so much vital information for
    me. And i’m glad studying your article. But should remark on few normal things,
    The web site taste is ideal, the articles is truly nice : D.
    Excellent job, cheers

  3. Its a Big Opportunity To Learn php Coding Practice For a Beginner.
    so i am very glad to your site where you given more tutorial.
    thanks a lot…..

  4. Aw, this was an extremely good post. Spending some time and actual effort to
    produce a superb article… but what can I say… I procrastinate a whole lot and never manage to get nearly anything
    done.

Leave a Reply

Your email address will not be published. Required fields are marked *


*