Friday, 24 May 2013

PHP If...Else Statements

Conditional statements are used to perform different actions based on different conditions.

PHP Conditional Statements

Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this.
In PHP we have the following conditional statements:
  • if statement - executes some code only if a specified condition is true
  • if...else statement - executes some code if a condition is true and another code if the condition is false
  • if...else if....else statement - selects one of several blocks of code to be executed
  • switch statement - selects one of many blocks of code to be executed

PHP - The if Statement

The if statement is used to execute some code only if a specified condition is true.

Syntax

if (condition)
  {
  code to be executed if condition is true
;
 
}
The example below will output "Have a good day!" if the current time is less than 20:

Example

<?php
$t=date("H");
if ($t<"20")
  {
  echo "Have a good day!";
  }
?>


PHP - The if...else Statement

Use the if....else statement to execute some code if a condition is true and another code if the condition is false.

Syntax

if (condition)
 {
  code to be executed if condition is true;
 }
else
 {
  code to be executed if condition is false;
 
}
The example below will output "Have a good day!" if the current time is less than 20, and "Have a good night!" otherwise:

Example

<?php
$t=date("H");
if ($t<"20")
  {
  echo "Have a good day!";
  }
else
  {
  echo "Have a good night!";
  }
?>

PHP Operators

The assignment operator = is used to assign values to variables in PHP.
The arithmetic operator + is used to add values together in PHP.

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 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

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

<?php
$txt="Hello world!";
echo $txt;
?> 
 
lamp 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

<?php
$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!
Tip: 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

<?php
echo strlen("Hello world!");
?> 
 
The output of the code above will be: 12
Tip: 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

<?php
echo strpos("Hello world!","world");
?> 
 
The output of the code above will be: 6.
Tip: 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.

Complete PHP String Reference

For a complete reference of all string functions, go to our complete PHP String Reference.
The PHP string reference contains description and example of use, for each function!
 
 
 
 

PHP Variables

Variables are "containers" for storing information:

Example

<?php
$x=5;
$y=6;
$z=$x+$y;
echo $z;
?> 

Much Like Algebra

x=5
y=6
z=x+y
In algebra we use letters (like x) to hold values (like 5).
From the expression z=x+y above, we can calculate the value of z to be 11.
In PHP these letters are called variables.
lamp Think of variables as containers for storing data.


PHP Variables

As with algebra, PHP variables can be used to hold values (x=5) or expressions (z=x+y).
Variable can have short names (like x and y) or more descriptive names (age, carname, totalvolume).
Rules for PHP variables:
  • A variable starts with the $ sign, followed by the name of the variable
  • A 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)
lamp Both PHP statements and PHP variables are case-sensitive.

Creating (Declaring) PHP Variables

PHP has no command for declaring a variable.
A variable is created the moment you first assign a value to it:
$txt="Hello world!";
$x=5;
After the execution of the statements above, the variable txt will hold the value Hello world!, and the variable x will hold the value 5.
Note: When you assign a text value to a variable, put quotes around the value.

PHP is a Loosely Typed Language

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, we will have to declare (define) the type and name of the variable before using it.

PHP Variable Scopes

The scope of a variable is the part of the script where the variable can be referenced/used.
PHP has four different variable scopes:
  • local
  • global
  • static
  • parameter

Local Scope

A variable declared within a PHP function is local and can only be accessed within that function:

Example

<?php
$x=5; // global scope

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

myTest();
?> 
The script above will not produce any output because the echo statement refers to the local scope variable $x, 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

A variable that is defined outside of any function, has a global scope.
Global variables can be accessed from any part of the script, EXCEPT from within a function.
To access a global variable from within a function, use the global keyword:

Example

<?php
$x=5; // global scope
$y=10; // global scope

function myTest()
{
global $x,$y;
$y=$x+$y;
}

myTest();
echo $y; // outputs 15
?> 
PHP also stores all global variables in an array called $GLOBALS[index]. The index holds 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 like this:

Example

<?php
$x=5;
$y=10;

function myTest()
{
$GLOBALS['y']=$GLOBALS['x']+$GLOBALS['y'];
}

myTest();
echo $y;
?> 
 

Static Scope

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:

Example

<?php

function myTest()
{
static $x=0;
echo $x;
$x++;
}

myTest();
myTest();
myTest();

?>
 
 
 
 

PHP Syntax

The PHP script is executed on the server, and the plain HTML result is sent back to the browser.

Basic PHP Syntax

A PHP script can be placed anywhere in the document.
A PHP script starts with <?php and ends with ?>:
<?php
// 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 file, with a PHP script that sends the text "Hello World!" back to the browser:

Example

<!DOCTYPE html>
<html>
<body>

<h1>My first PHP page</h1>

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


</body>
</html> 
 

Comments in PHP

Example

<!DOCTYPE html>
<html>
<body>

<?php
//This is a PHP comment line

/*
This is
a PHP comment
block
*/
?>


</body>
</html>
 

PHP Installation

What Do I Need?

To start using PHP, you can:
  • Find a web host with PHP and MySQL support
  • Install a web server on your own PC, and then install PHP and MySQL

Use a Web Host With PHP Support

If your server has activated support for PHP you do not need to do anything.
Just create some .php files, place them in your web directory, and the server will automatically parse them for you.
You do not need to compile anything or install any extra tools.
Because PHP is free, most web hosts offer PHP support.

Set Up PHP on Your Own PC

However, if your server does not support PHP, you must:
  • install a web server
  • install PHP
  • install a database, such as MySQL
The official PHP website (PHP.net) has installation instructions for PHP: http://php.net/manual/en/install.php


Build Your Powerful HTML Website for Free with Wix

Start building your own stunning website - programming free!
Wix.com provides a free, easy-to-use online platform that lets you create and publish your own unique website. Its powerful editing tools & customizable website designs make building a beautiful website easy.
Add eCommerce features, connect a custom domain and experience superior SEO results. Wix is your ultimate solution for creating an exquisite HTML website.
Over 20 million users have created their website with Wix.
Create yours now! » 


PHP Tutorial



PHP PHP is a server scripting language, and is a powerful tool for making dynamic and interactive Web pages.
PHP is a widely-used, free, and efficient alternative to competitors such as Microsoft's ASP.

Easy Learning with "Show PHP"

Our "Show PHP" tool makes it easy to learn PHP, it shows both the PHP source code and the HTML output of the code.

Example

 

<!DOCTYPE html>
<html>
<body>

<?php
echo "My first PHP script!";
?>


</body>
</html>  


PHP code is executed on the server.

What You Should Already Know

Before you continue you should have a basic understanding of the following:
  • HTML
  • JavaScript
If you want to study these subjects first, find the tutorials on our Home page.

What is PHP?

  • 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
lamp PHP is simple for beginners.

PHP also offers many advanced features for professional programmers.


What is a 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"

What Can PHP 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.

Why PHP?

  • 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
  • PHP is free. Download it from the official PHP resource: www.php.net
  • PHP is easy to learn and runs efficiently on the server side