PHP Basic


PHP Tags

Long tag
<?php ………………… ?>
This is the default enabled tag of php.

Short tag
<? ………………. ?>
By default this tag is not enabled, we need to enable it using php.ini file
ASP like tag
<% ………………. %>
For PHP ASP like tags were introduced to attract the ASP developers. This also need to enabled using php.ini file.


.

<?php
  echo "Hi! I'm Logn Tag";
?>

<?
  echo "Hi! I'm Short Tag";
?>

<%
  echo "Hi! I'm Tradtional ASP like tag";
%>
 
                                                     
 
Tag.php

PHP Comments
Comments are the way you can specify, what you going to do with the program or command. During the execution of the scripts, comments are not going to interpret.
PHP has three Types of comments.

Single line Comment

// this is a single line comment

Multiple line comment (C like comments)

/* this is
    Multiple line
    Comment*/

Shell script like comment
This is also single line comment.

# Another single line comment


Add some comments to your previous php script and see the out put.




Variables


A variable is a means of storing a value, such as text string "Hello World!" or the integer value 4. A variable can then be reused throughout your code, instead of having to type out the actual value over and over again. In PHP you define a variable with the following form:

$variable_name = Value;
You assign a value to the variable using the assignment operator (=).
If you forget that dollar, it will not work.

NOTE: Also, variable names are case-sensitive, so use the exact same capitalization when using a variable. The variables $a_number and $A_number are different variables in PHP.

Note for programmers: PHP does not require variables to be declared before being initialized.

$variable = 2;
$variable = 'A';
$variable = 'This is a sentence.';
 
 
  

PHP Variable Naming Conventions

v  There are a few rules that you need to follow when choosing a name for your PHP variables.
v  PHP variables must start with a letter or underscore "_".
v  PHP variables may only be comprised of alpha-numeric characters and underscores. a-z, A-Z, 0-9, or _ .
v  Variables with more than one word should be separated with underscores. $my_variable
v  Variables with more than one word can also be distinguished with capitalization. $myVariable


Predefine variables

PHP provides a large number of predefined variables to all scripts. The variables represent everything from external variables to built-in environment variables, last error messages to last retrieved headers.

  • Superregionals — Superglobals are built-in variables that are always available in all scopes
  • $GLOBALS — References all variables available in global scope
  • $_SERVER — Server and execution environment information
  • $_GET — HTTP GET variables
  • $_POST — HTTP POST variables
  • $_FILES — HTTP File Upload variables
  • $_REQUEST — HTTP Request variables
  • $_SESSION — Session variables
  • $_ENV — Environment variables
  • $_COOKIE — HTTP Cookies
  • $php_errormsg — The previous error message
  • $HTTP_RAW_POST_DATA — Raw POST data
  • $http_response_header — HTTP response headers
  • $argc — The number of arguments passed to script
  • $argv — Array of arguments passed to scrjtmnipt

Constants
A constant is an identifier (name) for a simple value. As the name suggests, that value cannot change during the execution of the. A constant is case-sensitive by default. By convention, constant identifiers are always uppercase.


<?php

// Valid constant names
define("FOO",     "something");
define("FOO2",    "something else");
define("FOO_BAR", "something more");

// Invalid constant names
define("2FOO",    "something");

// This is valid, but should be avoided:
// PHP may one day provide a magical constant
// that will break your script
define("__FOO__", "something");

?>
 
 




Printing Variable Values

If you want to print a value of a variable you can directly print it using “echo”.

<?php
$variable = 'printing out a variable here.';
echo $variable;
?>
 
 
Use of Double Quote and Single Quote
There are two different ways of printing text using PHP script. Using double or single quoted.


<?php
  echo "This is a double quoted string";
 
  echo 'This is a single quoted string';
?>
 
 
 


What is the different between Double Quote and Single Quote?
<?php

$variable = 'Saman';
echo 'My name is $variable';
?>
<?php

$variable = 'Saman';
echo "My name is $variable";
?>
Double_quote.php Single_quote.php
Execute above scrip and observe the difference.
If a variable is to be printed out amongst the words of a string then the whole thing must be contained within double quotes. If we wish to interpolate a variable into a sentence this is how we do it. Why, though? What if we used single quotes?


<?php
$variable = 'Saman';
$myname =  'My name is '.$variable;
echo $myname;
?>
 
Alternative Way with Single Quote


v  “.” is the string concatenation operator in PHP.


Data Types of PHP

·         Booleans
This is the simplest type. A Boolean expresses a truth value. It can be either TRUE or FALSE.
·         Integers
An integer is a number of the set Z = {..., -2, -1, 0, 1, 2, ...}.
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 size can be determined using the constant PHP_INT_SIZE, and maximum value using the constant PHP_INT_MAX

$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)
          
·         Floating point numbers
Floating point numbers (also known as "floats", "doubles", or "real numbers") can be specified using any of the following syntaxes:
$a = 1.234;
$b = 1.2e3;
$c = 7E-10;

·         Strings
A string is series of characters. Before PHP 6, a character is the same as a byte. That is, there are exactly 256 different characters possible.
·         Arrays
An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible.
$arr = array("foo" => "bar", 12 => true);
·         Objects
Instance of a Class is call as an object. Using new key word we create object
·         Resources
A resource is a special variable, holding a reference to an external resource. Resources are created and used by special functions.
·         NULL
The special NULL value represents a variable with no value. NULL is the only possible value of type NULL.

A variable is considered to be null if:
·         it has been assigned the constant NULL.
·         it has not been set to any value yet.
·         it has been unset().

Four scalar types:
  • boolean           integer            float                string
Two compound types:
  • array               object
The type of a variable is usually not set by the programmer; rather, it is decided at runtime by PHP depending on the context in which that variable is used.
To get the data type of some particular variable, we can use gettype() function.


<?php
$varint=12;
$vardouble=12.12;
$varstring1="test";
$varstring2='test';
$varbool=true;
echo gettype($varint)."<br>";
echo gettype($vardouble)."<br>";
echo gettype($varstring1)."<br>";
echo gettype($varstring2)."<br>";
echo gettype($varbool)."<br>";
?>

 
 

Arithmetic Operators

Arithmetic Operators

Example
Name
Result
-$a
Negation
Opposite of $a.
$a + $b
Addition
Sum of $a and $b.
$a - $b
Subtraction
Difference of $a and $b.
$a * $b
Multiplication
Product of $a and $b.
$a / $b
Division
Quotient of $a and $b.
$a % $b
Modulus
Remainder of $a divided by $b.
$a++
Increment
$a+1
$a--
Decrement
$a-1

Example on Arithmetic Expressions

<?php
$a = 4;
$b = 2;
$m=$a + $b ;
$n= $a - $b ;
$p= $a * $b ;
$q=$a / $b;
$r=$a % $b;
$s=$a++;
$t=$a--;
echo '$a + $b:'.$m."<BR>";
echo '$a - $b:'.$n."<BR>";
echo '$a * $b:'.$p."<BR>";
echo '$a / $b:'.$q."<BR>";
echo '$a % $b:'.$r."<BR>";
echo '$a++:'.$s."<BR>";
echo '$a--:'.$t."<BR>";
?>
 
 
Assignment Operators

The basic assignment operator is "=". Your first inclination might be to think of this as "equal to". Don't. It really means that the left operand gets set to the value of the expression on the rights (that is, "gets set to").



<?php
$a = 3;
echo $a.BR>;
$a += 5; // sets $a to 8, as if we had said: $a = $a + 5;
echo $a;
$b = "Hello ";
echo $b;
$b .= "There!"; // sets $b to "Hello There!", just like $b = $b . "There!";
echo $b;
?>
 
 












Note: The assignment copies the original variable to the new one (assignment by value), so changes to one will not affect the other.

Comparison Operators

Comparison Operators
Example
Name
Result
$a == $b
Equal
TRUE if $a is equal to $b.
$a === $b
Identical
TRUE if $a is equal to $b, and they are of the same type. (introduced in PHP 4)
$a != $b
Not equal
TRUE if $a is not equal to $b.
$a <> $b
Not equal
TRUE if $a is not equal to $b.
$a !== $b
Not identical
TRUE if $a is not equal to $b, or they are not of the same type. (introduced in PHP 4)
$a < $b
Less than
TRUE if $a is strictly less than $b.
$a > $b
Greater than
TRUE if $a is strictly greater than $b.
$a <= $b
Less than or equal to
TRUE if $a is less than or equal to $b.
$a >= $b
Greater than or equal to
TRUE if $a is greater than or equal to $b.

Logical Operators

Logical Operators
Example
Name
Result
$a and $b
And
TRUE if both $a and $b are TRUE.
$a or $b
Or
TRUE if either $a or $b is TRUE.
$a xor $b
Xor
TRUE if either $a or $b is TRUE, but not both.
! $a
Not
TRUE if $a is not TRUE.
$a && $b
And
TRUE if both $a and $b are TRUE.
$a || $b
Or
TRUE if either $a or $b is TRUE.



Flow Control


If….else Condition

Syntax: if (condition here) { } 
if (condition here) { }
 else { }
Example

<?php
$a=8;
$b=9;

if ($a < $b)
    echo "a is less than b";
else
    echo "a is bigger than b";

if ($a > $b)
{

    echo "a is bigger than b";
    echo "b is less than a";

}
?> 
 
 

If …elseif…else Condition

Syntax: if (condition here) { }
              elseif ( another condition here ) { }
              elseif ( yet another condition here ) { }
              else  { }            //none of the other conditions

Example

<?php
$a = 2;
$b = 1;
if($a == $b) {
    echo 'value in $a is equal to the value in $b';
}
elseif($a > $b) {
    echo 'value in $a is greater than value in $b';
}
else {
    echo 'value in $a is NOT greater than OR equal to the value in $b, so it must be less';
}
?>
 
 

Question:

Write a program to if marks value is given calculate the Grade of the subject.
Marks >80: Grade A
Marks between 70 and 80: Grade B
Marks between 60 and 70: Grade C
Else: Fail

While loop

Syntax: WHILE (condition here) {}

Example

<?php

$var = 1;

while($var < 11) {
          echo $var.' ';
          $var++;
}

?>
 
 

do-while loop

Syntax: do { } while (Condition here);
?>

Example

<?php
$i = 0;

do {
    echo $i;
} while ($i > 0);

?>
 
 

For loop

Syntax: for (first condition, test condition,    increment condition   ) { }

Example

<?php

for ($i=1;$i<11;$i++)
{
          echo $i.' ';
}

?>
 
 


Foreach loop

This simply gives an easy way to iterate over arrays. foreach works only on arrays, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable.

Syntax: foreach( array_expression as $value){ }
              foreach( array_expression as $key => $value){ }
             
We will discuss this under arrays.

Continue and break
  • Break ends execution of the current for, foreach, while, do-while or switch structure.
  • Continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration.



<?php
$i = 0;
do {
    echo $i."<BR>";
    if($i<10)
    {
          echo "Continue"."<BR>";
          $i++;
          continue;
    }
    else if($i==10)
    {
          echo "Break"."<BR>";
          break;
    }
    $i++;
} while ($i<=20);
?>
 
 















Switch ….Case
The switch statement is similar to a series of IF statements on the same expression. In many occasions, you may want to compare the same variable (or expression) with many different values, and execute a different piece of code depending on which value it equals to. This is exactly what the switch statement is for.

<?php
$i=1;
if ($i == 0) {
    echo "i equals 0";
} elseif ($i == 1) {
    echo "i equals 1";
} elseif ($i == 2) {
    echo "i equals 2";
}

switch ($i) {
case 0:
    echo "i equals 0";
    break;
case 1:
    echo "i equals 1";
    break;
case 2:
    echo "i equals 2";
    break;
}

?>
 
 

String Manipulation


Strings
A string is series of characters. Before PHP 6, a character is the same as a byte. That is, there are exactly 256 different characters possible. This also implies that PHP has no native support of Unicode.
A string literal can be specified in four different ways:
·         single quoted
·         double quoted
·         heredoc syntax
·         nowdoc syntax
Quoted Strings

The easiest way to specify a simple string is to enclose it in single quotes (the character '). Enclosing the string in double-quotes ("), will allow PHP to understand additional escape sequences for special characters:

Example:

<?php
$str_1 = 'I am a string in single quotes'; 
$str_2 = "I am a string in double quotes"; 
?>
 
 

Escape Characters

Escaped characters
Sequence
Meaning
\n
Line feed (LF or 0x0A (10) in ASCII)
\r
carriage return (CR or 0x0D (13) in ASCII)
\t
horizontal tab (HT or 0x09 (9) in ASCII)
\v
vertical tab (VT or 0x0B (11) in ASCII) (since PHP 5.2.5)
\f
form feed (FF or 0x0C (12) in ASCII) (since PHP 5.2.5)
\\
backslash
\$
dollar sign
\"
double-quote
\[0-7]{1,3}
the sequence of characters matching the regular expression is a character in octal notation
\x[0-9A-Fa-f]{1,2}
the sequence of characters matching the regular expression is a character in hexadecimal notation
Example

<?php
echo 'this is a simple string';

echo 'You can also have embedded newlines in
strings this way as it is
okay to do';

// Outputs: Arnold once said: "I'll be back"
echo 'Arnold once said: "I\'ll be back"';

// Outputs: You deleted C:\*.*?
echo 'You deleted C:\\*.*?';

// Outputs: You deleted C:\*.*?
echo 'You deleted C:\*.*?';

// Outputs: This will not expand: \n a newline
echo 'This will not expand: \n a newline';

// Outputs: Variables do not $expand $either
echo 'Variables do not $expand $either';
?>
 
 

Concatenating Strings
Using the concatenate operator (.), strings can be easily joined together.

<?php 
$str_1 = 'This';
$str_2 = 'is a';
$str_3 = 'string.';
$str = $str_1. " " .$str_2. " " .$str_3;
echo $str;
?>



Heredoc syntax

In order to allow people to easily write large amounts of text from within PHP, but without the need to constantly escape things, heredoc syntax was developed. Heredoc might be a little tricky to understand at first, but it is actually a big help. Put simply, it allows you to define your own string limiter so that you can make it something other than a double or single quote.

Example

<?php
$mystring = <<<EOT
   This is some PHP text.
   It is completely free
   I can use "double quotes"
   and 'single quotes',
   plus $variables too, which will
   be properly converted to their values,
   you can even type EOT, as long as it
   is not alone on a line, like this:
EOT;
Echo $mystring’;
?>

 
 

There are several key things to note about heredoc, and the example above:
  • You can use anything you like; "EOT" is just an example
  • You need to use <<< before the delimiter to tell PHP you want to enter heredoc mode
  • Variable substitution is used in PHP, which means you do need to escape dollar symbols – if you do not, PHP will attempt variable replacement.
  • You can use your delimiter anywhere in the text, but not in the first column of a new line
  • At the end of the string, just type the delimiter with no spaces around it, followed by a semi-colon to end the statement


Nowdoc syntax

Introduced with PHP 5.3.0 students need to find about this.



String Manipulation functions

trim() : Removes leading and tailoring spaces
strtolower():Returns string with all alphabetic characters converted to uppercase
strtoupper():Returns string with all alphabetic characters converted to lowercase
substr() : Returns the portion of string specified by the start and length parameters
strcmp(): Compare two strings, this is a case sensitive comparison
strlen(): Return the length of a string

Examples on String manipulation function

<?php

$val="   Test String";
$val2="aBC";
echo "Trim: ".trim($val)."<BR>";
echo "LowerCase: ".strtolower($val2)."<BR>";
echo "UpperCase: ".strtoupper($val2)."<BR>";
echo "Sub String: ".substr($val, -3, 1)."<BR>";
echo "Sub String: ".substr($val, 6, 3)."<BR>";
echo "Compare String: ".strcmp($val,$val2)."<BR>";
echo "Length : ".strlen($val)."<BR>";

?>
 
 

Exercises & Practices
1 What is “var_dump” ? Give an eexample on “var_dump”.
2 Write a program to print 1 to 100.
3 “-----071-3234443-----“this is a string got out from a communication line. This string should contain a telephone number. But it contains leading and tailoring dashes. Write a program to retrieve the telephone number. *Hint use string manipulation functions.








No comments:

Form Processing with PHP

Form Processing with PHP PHP "superglobals" Several predefined variables in PHP are "superglobals", which mean...