Custom Search

Thursday, February 21, 2013

PHP OPERATORS


PHP Operators

       An operator is a special symbol which indicates a certain process is carried out. Operators in programming languages are taken from mathematics. Programmers work with data. The operators are used to process data.

We have several types of operators:
  • Arithmetic operators
  • Boolean operators
  • Relational operators
  • Bitwise operators
An operator may have one or two operands. An operand is one of the inputs (arguments) of an operator. Those operators that work with only one operand are called unary operators. Those who work with two operands are called binary operators.
+ and - signs can be addition and subtraction operators as well as unary sign operators. It depends on the situation.

php > print +2;
2
php > print -2;
-2
php > print 2;
2
php > print 2+2;
4
php > print 2-2;
0

The plus sign can be used to indicate that we have a positive number. But it is mostly not used. The minus sign changes the sign of a value.

PHP Arithmetic Operators

Operator
Name
Description
Example
Result
x + y
Addition
Sum of x and y
2 + 2
4
x - y
Subtraction
Difference of x and y
5 - 2
3
x * y
Multiplication
Product of x and y
5 * 2
10
x / y
Division
Quotient of x and y
15 / 5
3
x % y
Modulus
Remainder of x divided by y
5 % 2
10 % 8
10 % 2
1
2
0
- x
Negation
Opposite of x
- 2

a . b
Concatenation
Concatenate two strings
"Hi" . "Ha"
HiHa

PHP Assignment Operators

The basic assignment operator in PHP is "=". It means that the left operand gets set to the value of the expression on the right. That is, the value of "$x = 5" is 5.

Assignment
Same as...
Description
x = y
x = y
The left operand gets set to the value of the expression on the right
x += y
x = x + y
Addition
x -= y
x = x - y
Subtraction
x *= y
x = x * y
Multiplication
x /= y
x = x / y
Division
x %= y
x = x % y
Modulus
a .= b
a = a . b
Concatenate two strings
PHP Incrementing/Decrementing Operators

Operator
Name
Description
++ x
Pre-increment
Increments x by one, then returns x
x ++
Post-increment
Returns x, then increments x by one
-- x
Pre-decrement
Decrements x by one, then returns x
x --
Post-decrement
Returns x, then decrements x by one


PHP Comparison Operators

Comparison operators allows you to compare two values:

Operator
Name
Description
Example
x == y
Equal
True if x is equal to y
5==8 returns false
x === y
Identical
True if x is equal to y, and they are of same type
5==="5" returns false
x != y
Not equal
True if x is not equal to y
5!=8 returns true
x <> y
Not equal
True if x is not equal to y
5<>8 returns true
x !== y
Not identical
True if x is not equal to y, or they are not of same type
5!=="5" returns true
x > y
Greater than
True if x is greater than y
5>8 returns false
x < y
Less than
True if x is less than y
5<8 o:p="" returns="" true="">
x >= y
Greater than or equal to
True if x is greater than or equal to y
5>=8 returns false
x <= y
Less than or equal to
True if x is less than or equal to y
5<=8 returns true
PHP Logical Operators

Operator
Name
Description
Example
x and y
And
True if both x and y are true
x=6
y=3
(x < 10 and y > 1) returns true
x or y
Or
True if either or both x and y are true
x=6
y=3
(x==6 or y==5) returns true
x xor y
Xor
True if either x or y is true, but not both
x=6
y=3
(x==6 xor y==3) returns false
x && y
And
True if both x and y are true
x=6
y=3
(x < 10 && y > 1) returns true
x || y
Or
True if either or both x and y are true
x=6
y=3
(x==5 || y==5) returns false
! x
Not
True if x is not true
x=6
y=3
!(x==y) returns true





PHP Array Operators
Operator
Name
Description
x + y
Union
Union of x and y
x == y
Equality
True if x and y have the same key/value pairs
x === y
Identity
True if x and y have the same key/value pairs in the same order and are of the same type
x != y
Inequality
True if x is not equal to y
x <> y
Inequality
True if x is not equal to y
x !== y
Non-identity
True if x is not identical to y

Operator precedence

The operator precedence tells us which operators are evaluated first. The precedence level is necessary to avoid ambiguity in expressions.

What is the outcome of the following expression? 28 or 40?
 3 + 5 * 5

Like in mathematics, the multiplication operator has a higher precedence than addition operator. So the outcome is 28.

(3 + 5) * 5
To change the order of evaluation, we can use square brackets. Expressions inside square brackets are always evaluated first.

The following list shows 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
<< >>
bitwise
< <= > >= <>
comparison
== != === !==
comparison
&&
logical "and"
||
logical "or"
? :
ternary operator
= += -= *= /= .= %=
assignment
and
logical "and"
xor
logical "xor"
or
logical "or"
,
comma operator

Operators on the same line in the list have the same precedence.


print 3 + 5 * 5;
print "\n";
print (3 + 5) * 5;
print "\n";

var_dump(! True or True);
var_dump(! (True or True));

?>

In this code example, we show some common expressions. The outcome of each expression is dependent on the precedence level.

var_dump(! True or True);

In this case, the negation operator has a higher precedence. 
First, the first True value is negated to False, than the or operator combines False and True, which gives True in the end.

$ php precedence.php
28
40
bool(true)
bool(false)

The relational operators have a higher precedence than logical operators.


$a = 1;
$b = 2;

if ($a > 0 and $b > 0) {

    echo "\$a and \$b are positive integers\n";
}

?>

The and operator awaits two boolean values.

 If one of the operands would not be a boolean value, we would get a syntax error.
 In PHP, the relational operators are evaluated first. 
The logical operator then.
$ php positive.php
$a and $b are positive integers

Associativity

Sometimes the precedence is not satisfactory to determine the outcome of an expression. 

There is another rule called associativity. 

The associativity of operators determines the order of evaluation of operators with the same precedence level.

9 / 3 * 3

What is the outcome of this expression? 9 or 1? The multiplication, deletion and the modulo operator are left to right associated. 

So the expression is evaluated this way: (9 / 3) * 3 and the result is 9.

Arithmetic, boolean, relational and bitwise operators are all left to right associated.
On the other hand, the assignment operator is right associated.

php > $a = $b = $c = $d = 0;
php > echo $a, $b, $c, $d;
0000

If the association was left to right, the previous expression would not be possible.
The compound assignment operators are right to left associated.

php > $j = 0;
php > $j *= 3 + 1;
php > print $j;
0

You might expect the result to be 1. 

But the actual result is 0.

 Because of the associativity. 

The expression on the right is evaluated first and than the compound assignment operator is applied.

Other operators

PHP has a silence ( @ ) operator. It is used to turn off error messaging. It is typically used with network or database connections. This operator should be used with caution, because it can lead to debugging issues.
php > echo 3 / 0;

Warning: Division by zero in php shell code on line 1

php > echo @ (3 / 0);
php >

In the first case, we receive a division by zero error message. In the second case, the @ operator turns off the error message.

The reference ( & ) operator. It creates a reference to an object.

php > $a = 12;
php > $b = &$a;
php > echo $b;
12
php > $b = 24;
php > echo $b;
24
php > echo $a;
24

In the above example, we pass a value to $a variable and pass a reference to the $a to the $b variable.

php > $b = &$a;

We create a new variable $b pointing to the $a variable. In other words, we create an alias for the $a variable.

php > $b = 24;
php > echo $b;
24
php > echo $a;
24

Assigning a new value to $b will also affect the $a.

The backtick ( ` ) operator

It is used to execute commands. 

It is identical to the shell_exec()function call.

php > $list = `ls -l`;
php > echo $list;
total 48

-rw-r--r-- 1 vronskij vronskij 127 2009-12-07 11:25 andop.php
-rw-r--r-- 1 vronskij vronskij 174 2009-12-07 10:48 arithmetic.php
-rw-r--r-- 1 vronskij vronskij  86 2010-01-16 15:11 atoperator.php
-rw-r--r-- 1 vronskij vronskij 106 2009-12-07 12:25 compare.php

Execute an ls command, which on Unix systems lists the contents of the current directory.

STRING FUNCTION IN PHP


PHP String Variables

              A string variable is used to store and manipulate text.

String Variables in PHP
  • String variables are used for values that contain characters.
  • After we have created a string variable we can manipulate it. 
  • A string can be used directly in a function or it can be stored in a variable.
  • In the example below, we create a string variable called txt, then we assign the text "Hello world!" to it. Then we write the value of the txt variable to the output:

Example

$txt="Hello world!";
echo $txt;
?>

Note: When you assign a text value to a variable, remember to put single or double quotes around the value.
Now, lets look at some commonly used functions and operators to manipulate strings.

The PHP Concatenation Operator
  • There is only one string operator in PHP.
  • The concatenation operator (.)  is used to join two string values together.

The example below shows how to concatenate two string variables together:
Example

$txt1="Hello world!";
$txt2="What a nice day!";
echo $txt1 . " " . $txt2;
?>

The output of the code above will be: Hello world! What a nice day!

Note: In the code above we have used the concatenation operator two times. This is because we wanted to insert a white space between the two strings.

The PHP strlen() function
  • Sometimes it is useful to know the length of a string value.
  • The strlen() function returns the length of a string, in characters.

The example below returns the length of the string "Hello world!":

Example
echo strlen("Hello world!");
?>

The output of the code above will be: 12

Note: strlen() is often used in loops or other functions, when it is important to know when a string ends. (i.e. in a loop, we might want to stop the loop after the last character in a string).

The PHP strpos() function

  • The strpos() function is used to search for a character or a specific text within a string.
  • If a match is found, it will return the character position of the first match. If no match is found, it will return FALSE.

The example below searches for the text "world" in the string "Hello world!":
Example

echo strpos("Hello world!","world");
?>

The output of the code above will be: 6.

Note: The position of the string "world" in the example above is 6. The reason that it is 6 (and not 7), is that the first character position in the string is 0, and not 1.

Sunday, January 13, 2013

PHP


PHP is an open source server-side scripting language designed for Web development to produce dynamic Web pages. It is one of the first developed server-side scripting languages to be embedded into an HTML source document rather than calling an external file to process data. The code is interpreted by a Web server with a PHP processor module which generates the resulting Web page. It also has evolved to include a command-line interface capability and can be used in standalone graphical applications.  A competitor to Microsoft's Active Server Pages (ASP) server-side script engine and similar languages, PHP is installed on more than 20 million Web sites and 1 million Web servers Notable software that uses PHP includes 

Definition: The echo () function is used to output the given argument. It can output all types of data and multiple outputs can be made with only one echo () command.
Examples:
 Echo "Hello";
 //Outputs a string
 Echo $variable;
 //Outputs a variable
 Echo "Multiple things " . $on . " one line";
 //Outputs a string, then a variable, then a string. All are separated with a [.] period
 ?>

What You Should Already Know
Before you continue you should have a basic understanding of the following:
  •     HTML
  •     JavaScrip
PHP Means
  •  PHP stands for PHP: Hypertext Preprocessor
  • PHP is a widely-used, open source scripting language
  • PHP scripts are executed on the server
  • PHP is free to download and use
PHP File
  • PHP files can contain text, HTML, JavaScript code, and PHP code
  • PHP code are executed on the server, and the result is returned to the browser as plain HTML
  • PHP files have a default file extension of ".php"
PHP Can Do
  • PHP can generate dynamic page content
  • PHP can create, open, read, write, and close files on the server
  • PHP can collect form data
  • PHP can send and receive cookies
  • PHP can add, delete, modify data in your database
  • PHP can restrict users to access some pages on your website
  • PHP can encrypt data
With PHP you are not limited to output HTML. You can output images, PDF files, and even Flash movies. You can also output any text, such as XHTML and XML
PHP Uses
  • PHP runs on different platforms (Windows, Linux, Unix, Mac OS X, etc.)
  • PHP is compatible with almost all servers used today (Apache, IIS, etc.)
  • PHP has support for a wide range of databases
XML Tools
Integrated suite of tools ideal for:
  • XML development
  • Web & Web services development
  • Data mapping & integration
  • Rendering & publishing XML & database data
  • XBRL validation, taxonomy editing, transformation & rendering
  • Chart & report generation for XML & XBRL



PHP Syntax
A PHP script always starts with  and ends with ?>. A PHP script can be placed anywhere in the document.
On servers with shorthand-support, you can start a PHP script with .
For maximum compatibility, we recommend that you use the standard form (
// PHP code goes here
?>
The default file extension for PHP files is ".php".
A PHP file normally contains HTML tags, and some PHP scripting code.
Below, we have an example of a simple PHP script that sends the text "Hello World!" back to the browser:
Example




echo "Hello World!";
?>




Algebra x=5, y=6, z=x+y
These letters are called variables, and variables can be used to hold values (x=5) or expressions (z=x+y).

PHP Variables
A variable can have a short name, like x, or a more descriptive name, like carName.
Rules for PHP variable
    •      Variables in PHP starts with a $ sign, followed by the name of the variable
    •       The variable name must begin with a letter or the underscore character
    •      A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
    •      A variable name should not contain spaces
    •      Variable names are case sensitive (y and Y are two different variables)
Creating (Declaring) PHP
PHP has no command for declaring a variable.
A variable is created the moment you first assign a value to it:
$myCar="Volvo";
After the execution of the statement above, the variable myCar will hold the value Volvo.
Tip: If you want to create a variable without assigning it a value, then you assign it the value ofnull.
Let's create a variable containing a string, and a variable containing a number:
$txt="Hello World!";
$x=16;
?>

PHP is a Loosely Typed Language
In PHP, a variable does not need to be declared before adding a value to it.
In the example above, notice that we did not have to tell PHP which data type the variable is.
PHP automatically converts the variable to the correct data type, depending on its value.
In a strongly typed programming language, you have to declare (define) the type and name of the variable before using it.

PHP Variable Scope
  •        local
  •        global
  •        static
  •        parameter

Local Scope
A variable declared within a PHP function is local and can only be accessed within that function. (the variable has local scope):
$a = 5; // global scope

function myTest()
{
echo $a; // local scope
}
 

myTest();
?>
The script above will not produce any output because the echo statement refers to the local scope variable $a, which has not been assigned a value within this scope.
You can have local variables with the same name in different functions, because local variables are only recognized by the function in which they are declared.
Local variables are deleted as soon as the function is completed.

Global Scope
Global scope refers to any variable that is defined outside of any function.
Global variables can be accessed from any part of the script that is not inside a function.
To access a global variable from within a function, use the global keyword:
$a = 5;
$b = 10;

function myTest()
{
global $a, $b;
$b = $a + $b;
}
 

myTest();
echo $b;
?>
The script above will output 15.
PHP also stores all global variables in an array called $GLOBALS[index]. Its index is the name of the variable. This array is also accessible from within functions and can be used to update global variables directly.
The example above can be rewritten as this:
$a = 5;
$b = 10;

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


myTest();
echo $b;
?>


Setatic Scop
When a function is completed, all of its variables are normally deleted. However, sometimes you want a local variable to not be deleted.
To do this, use the static keyword when you first declare the variable:
static $rememberMe;
Then, each time the function is called, that variable will still have the information it contained from the last time the function was called.

Parameters
 parameter is a local variable whose value is passed to the function by the calling code.
Parameters are declared in a parameter list as part of the function declaration:
function myTest($para1,$para2,...)
{
// function code
}
Parameters are alAso called arguments. We will discuss them in more detail when we talk about functions.



Sunday, June 20, 2010

Flow Control and Iteration

Flow Control and Iteration
Flow control and iteration are two very useful features of most programming languages. Without them all programs would have to be linear and if you wanted something to happen three times, you would have to code it three times.
Flow control means exactly what it sounds like it should, controlling the flow of something. When using flow control for programming, what you are doing is regulating the order in which the code is executed, how many times it is executed, and if it is executed at all Programmatic flow control can be broken into three primary categories.

Conditionals
Conditionals allow us to specify wether or not to run a selected piece of code based on some prior condition. It is the first topic we will cover. It is broken into two lectures, the first is an introduction to conditionals. The second is a discussion of some of the more advanced tools available in PHP for comparing things.Iteration
Our next topic is iteration. Iteration, also known as looping, us to specify that a piece of code be run multiple times. Depending on circumstances, that can be one or more or zero or more times.
Functions Our last primary flow control tool is functions. Functions allow us to create named blocks of code to be called by name elsewhere in the script. This allows us to run a piece of code multiple times from multiple places in the script. It is also the first step to writing good, modular code. This section contains both a brief introduction to functions and a more detailed look at advanced function topics in PHP

what is use php

  • php is a scripting language that is often embedded into html to add functions html alone can't do. php allows you to collect, process and utilize data to create a desired output. in short, it let's you interact with your pages.
    php is able to preform a number of tasks including printing data, making numeric calculations and making simple boolean choices. from this you can create more complex loops and functions to make your page generate more specialized data,

Database Access
One of set modules control database access. Using PHP with MySQL has become common enough that the MySQL interface is now part of core PHP instead of a plug-in module. Most other databases have modules that can be included in a PHP build to allow access. PHP can access most any SQL or ODBC database. It can both read and write information in the database.

This opens up the door for a whole variety of online business applications that require data storage on the server. Because of this, PHP is becoming an increasingly popular tool for e-commerce.

File Access

PHP can read and write files. It can also do basic file and directory maintenance. Because of this, you can use it to do such things as edit documents remotely. It can also be used to search flat file collections for the existence of a given file or for the existence of information stored in files and return the results. Information does not need to be coded into a database just to be accessible.

It can also take content and use it to generate files in various formats, including HTML and PDF. It is an incrasingly popular tool for processing XML for HTTP distribution. It can also take data and use it to generate e-mail, which is can send out through most any standard mail protocol.

Its ability to work across multiple data sources and return multiple content types makes it an ideal tool for things like search engines and message boards.

Application Control

PHP started as an application control language. Specifically, it was designed to handle access logging for HTTP servers. This ability has expanded greatly and now PHP can even be used as a scripting language in such applications as Microsoft Word and Excel.

Graphics
PHP can not only manage text content, it can also manage graphic content. It can be used to create graphs and charts. It can be used to generate GIF and PNG images on the fly, allowing you, for instance, to have a button template that has the text added to it dynamically before being sent to the client. This means you don't need a new image for each button, just one image that has the text added as needed for each individual button.

Extensible
PHP is extensible. It is written in C and the underlying source can be expanded on with new modules written in the same. It is also open source, so engaging in such expansion is permitted and encouraged

What Can PHP Do?

PHP is a server-side scripting language whose primary purpose is to generate HTML content. Its creator, Rasmus Lerdorf defines it as "a cross-platform, HTML-embedded, server-side web scripting languageWith the current direction of the Web, it is easily being adapted to writing out all forms of XML content as well. The most recent version of PHP

It was originally developed as a set of server-side modules to perform some specific Web-server tasks on small, Unix-based Web servers. Since then PHP has grown beyond the work of one man writing some tools for his own use and into one of the most popular server-side scripting languages in the Web.

Three thing make PHP popular. The first is that it is easy: easy to implement, easy to learn, and easy to use. The second is that it is free. The third is that it runs on almost any Web server on almost any platform currently available.

PHP is both a scripting language and a collection of tools for performing various server-side functions in an HTTP, or Web, server. Since it is written as a collection of C-modules, it can go beyond server-side scripting and can also be used to execute scripts from the command line and for developing client-side GUI applications that can operate on most any platform.
The core features of PHP are built around the ability to process strings and arrays, as well as to work as an object-oriented programming language. Beyond this most of PHP is a collection of modules that can be added in on the server as needed to perform a large variety of specific tasks. In other words, it is a highly customizable application, and you can keept it small by only installing as much as you need to perform required tasks