Lesson 2: PHP Language Basic - TOP10

Lesson 2: PHP Language Basic

 1.  Introducing Variables A variable is a representation of a particular value, such as hello or                      87266721. By assigning a value to a variable, you can reference the variable in other places in            your  script, and that value will always remain the same (unless you change it). 
2.   Naming Your Variables In PHP, unlike some other programming languages, there is no restriction       In PHP, unlike some other programming languages, there is no restriction on the size of a variable       name. In addition, you are free to use both numeric and alphanumeric (character set consists of           the numbers 0 to 9 and letters A to Z) characters in a variable name. Additionally, variable names       are case sensitive, meaning that $VARNAME and $varname are two different variables.                       However, there are certain rules that you need to follow. These         include: 
         • Variable names should begin with a dollar($) symbol. 
         • Variable names can begin with an underscore. 
         • Variable names cannot begin with a numeric character. 
         • Variable names must be relevant and self-explanatory.
Here are some examples of valid and invalid variable names: $_varname  valid $book    valid sum   invalid: doesn’t start with dollar sign($) $18varname  invalid: starts with number; it doesn’t start with letter or underscore $x*y    invalid: contains multiply sign which only letters, digits, and underscore are allowed.  
A variable may hold a value of any type. There is no compile- or runtime type checking on variables. You can replace a variable's value with another of a different type: $varname = "Fred"; $ varname = 35; $ varname = array('PHP', 'JSP', 'ASP'); 

3. 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 = 'world'; ?> 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 echo "$a ${$a}"; ?>  
produces the exact same output as: <?php echo "$a $hello"; ?> i.e. they both produce: hello world.  

In order to use variable variables with arrays, you have to resolve an ambiguity problem. That is, if you write $$a[1] then the parser needs to know if you meant to use $a[1] as a variable, or if you wanted $$a as the variable and then the [1] index from that variable. The syntax for resolving this ambiguity is: ${$a[1]} for the first case and ${$a}[1] for the second. 

4. Data Types You will create two main types of variables in your PHP code: scalar and array. Scalar variables contain only one value at a time, and arrays contain a list of values or even another array.  
PHP provides four primitive data types: integers, floating point numbers, strings, and booleans. In addition, there are two compound data types: arrays and objects. - Integers: Integers are whole numbers. The range of integers in PHP is equivalent to the range of the long data type in C. On 32-bit platforms, integer values range from -2,147,483,648 to +2,147,483,647. PHP automatically converts larger values to floating point numbers if you happen to overflow the range. An integer can be expressed in decimal (base-10), hexadecimal (base-16), or octal (base-8). For example: $decimal=16; $hex=0x10; $octal=020; If you try to store a too-large integer in a variable, it will automatically be turned into a floating point number.  
- Floating Point Numbers: Floating point numbers (“floats” or “doubles”) represent decimal values. The range of floating point numbers in PHP is equivalent to the range of the double type in C. On most platforms, a double can be between 1.7E-308 to 1.7E+308. A double may be expressed either as a regular number with a decimal point or in scientific notation. For example: $var= 87.3446; $var= 0.88889992.  
- Strings: Text or numeric information, specified within double quotes (" ") or single quotes (' '). For example: $st = 'PHP is cool'; $st = "Computer Studies!";  

Double-quoted strings are subject to variable substitution and escape sequence handling, while single quotes are not. For example: $a="World"; echo "Hello\t$a\n"; 

This displays "Hello" followed by a tab and then "World" followed by a newline. In other words, variable substitution is performed on the variable $a and the escape sequences are converted to their corresponding characters. Contrast that with: $a=’World’; echo ‘Hello\t$a\n’; In this case, the output is exactly "Hello\t$a\n". There is no variable substitution or handling of escape sequences.  

The following table shows the escape sequences understood by PHP inside doublequoted strings.   



- Booleans: The boolean type only has two states: true and false. For example: $flag = true; Boolean values are most commonly used when the == or === operators perform a comparison and return the result.  

- Arrays: An array is a compound data type that can contain multiple data values, indexed either numerically or with strings. For example, an array of strings can be written like this: $var[0]="Hello"; $var[1]="World"; Note that when you assign array elements like this, you do not have to use consecutive numbers to index the elements. As a shortcut, PHP allows you to add an element onto the end of an array without specifying an index. For example: $var[ ] ="Test"; PHP picks the next logical numerical index. In this case, the "Test" element is given the index 

2 in our $var array: if the array has nonconsecutive elements, PHP selects the index value that is one greater than the current highest index value. This autoindexing feature is most useful when dealing with multiple-choice HTML <select> form elements, as we'll see in a later example.  

Although we have called strings a primitive data type, it is actually possible to treat a string as a compound data type, where each character in the string can be accessed separately. In other words, you can think of a string as an array of characters, where the first character is at index 0. Thus, you can pick the third character out of a string with: $string[2] To solve an ambiguity problem between strings and arrays, a new syntax has been introduced to dereference individual characters from strings: $string{2}   This syntax is equivalent to $string[2], and is preferable.    Arrays can also be indexed using strings; these kinds of arrays are called associative arrays:  $var["January"]=1; $var["February"]=2;   All arrays in PHP can be traversed safely with the following mechanism:    foreach($array as $key=>$value) { echo "array[$key]=$value<br />"; } This is the most common way to loop through each element of an array, whether it is a linear or an associative array.  
-  Objects: An object is a compound data type that can contain any number of variables and functions. PHP's support for objects is somewhat limited in Version 4. PHP Version 5 will improve the object oriented capabilities of PHP. In PHP 4, the object-oriented support is designed to make it easy to encapsulate data structures and functions in order to package them into reusable classes. Here's a simple example: class test { var $str = "Hello World!"; function functionName($str) { $this->str = $str; } } $class = new test; echo $class->str; $class-> functionName("Hello"); echo $class->str; This code creates a test object using the new operator. Then it sets a variable called str within the object. In object-speak, a variable in an object is known as a property of that object. The test object also defines a function, known as a method, called functionName(). This method uses the special purpose $this variable to change the value of the str property within that object.  

5. Variable References In PHP, references are how you create variable aliases. To make $ratana an alias for the variable $ funny_guy, use:  $ ratana =& $funny_guy; The old value of $ratana is lost. Instead, $ ratana is now another name for the value that is stored in $funny_guy 

Let’s take a look at the example below to get a bettering unsderstanding of variable references:  $reference = "Rock";  $aliase =& $reference;  $reference .= " rocks!";      print "\$aliase is $aliase<br />";  print "\$reference is $reference<br />";  $aliase = "Actor $aliase";  print "\$aliase is $aliase<br />";  print "\$reference is $reference";  By executing the code above, you will get the output like something below:   $aliase is Rock rocks! $reference is Rock rocks! $aliase is Actor Rock rocks! $reference is Actor Rock rocks! From the result, we can see two points: 1. If we update value of $reference, the value $aliase will be the same as the lasted updated $reference value. 2. If we update the value of $aliase, the value of $reference will also be updated.  
After the assignment, the two variables are alternate names for the same value. Unsetting a variable that is aliased does not affect other names for that variable's value, though:  $ reference = " Rock "; $aliase =& $reference; unset($reference); print $aliase;   // output: Rock

6. Type Casting As I already mentioned, you do not need to specify a type when you create a variable, but that doesn't mean the variables do not have types associated with them. You can explicitly set the type, known as type casting, by using the C-style syntax in which you put the type you want in brackets before the variable or expression. For example:  $var = (int)"123more"; Without the (int) in this example, PHP creates a string variable. With the explicit cast, however, we have created an integer variable with a value of 123. The following table shows the available cast operators in PHP. 


7. Understanding settype(), gettype() functions 7.1 settype() function        We use it for set the type of a variable.         Syntax:   settype ( $var , string $type )           Parameters:                                            $var     : The variable being converted.    $type  : Possibles values of type are: "boolean" (or, since PHP 4.2.0, "bool") "integer" (or, since PHP 4.2.0, "int") "float" (only possible since PHP 4.2.0, for older versions use the deprecated variant "double") "string" "array" "object" "null" (since PHP 4.2.0)  
            Examples:    <?php 
$foo = "5bar"; // string $bar = true;   // boolean  
settype($foo, "integer"); // $foo is now 5   (integer) settype($bar, "string");  // $bar is now "1" (string) 
?> 
 7.2  gettype() function          We use it for return the type of a variable.         Syntax:   gettype ( $var )  
                   Possibles values for the returned string are:            "boolean" "integer" "double" (for historical reasons "double" is returned in case of a float, and not   simply "float") "string" "array" "object" "resource" "NULL" "unknown type"  
             Warning Never use gettype() to test for a certain type, since the returned string may be subject to change in a future version. In addition, it is slow too, as it involves string comparison.                  Examples:    <?php $foo = true; echo gettype($foo); // output: boolean ?> 

8. Constant Variable   A constant is an identifier for a value that cannot change during the course of a   script. Once a constant has a value, it remains through its execution lifetime.   Constants can be user defined, or you can use some of the predefined constants   that PHP always has available. Unlike simple variables, constants do not have a   dollar sign before their name, and they are usually uppercase to show their   difference from a scalar variable.   Syntax: define("CONSTANT_NAME", value [, true | false]);  
   If we set the third parameter to true so we could access its value without worrying about case The function used to define a constant is called define(), and it requires the name of the constant and the value you want to give it. Here you define a constant called MYCONSTANT with a value of "This is a test of defining constants.". define("MYCONSTANT", "This is a test of defining constants.");  
Examples:    <?php 
define("MYCONSTANT", "This is a test of defining constants."); echo MYCONSTANT; // output: This is a test of defining constants. 
?>  
 Some predefined constants include:  • __FILE__   Return the path and file name of the script file being parsed. • __LINE__   Return the number of the line in the script being parsed. • __DIR__  Return the path of the script file being parsed. • DIRECTORY_SEPARATOR  Return the \ (on Windows) or / (on Unix) depending on OS(Operating System) • PHP_VERSION   Return the version of PHP in use. • PHP_OS  Return the operating system using PHP.    Example:   <?php    echo __FILE__ . "<br />";   // output: C:\wamp\www\PHP\test.php    echo __LINE__ . "<br />";   // output: 3    echo __DIR__ . "<br />";   // output: C:\wamp\www\PHP    echo DIRECTORY_SEPARATOR . "<br />";   // output: \    echo PHP_VERSION . "<br />";   // output: 5.3.5    echo PHP_OS . "<br />";   // output: WINNT ?>  
 defined()   Checks whether a given named constant exists  
9. Using Environment Variables in PHP $_SERVER is an array containing information such as headers, paths, and script locations. The entries in this array are created by the web server. There is no guarantee that every web server will provide any of these; servers may omit some, or provide others not listed here.  
 $_SERVER['PHP_SELF']  The filename of the currently executing script, relative to the document root. For instance, $_SERVER['PHP_SELF'] in a script at the address  http://localhost/php/global-variables/$_SERVER.php would be 

 /php/global-variables/$_SERVER.php    $_SERVER['GATEWAY_INTERFACE' ] What revision of the CGI specification the server is using. Example: 'CGI/1.1'.    
$_SERVER['SERVER_ADDR' ] The IP address of the server under which the current script is executing. For instance, $_SERVER['SERVER_ADDR '] in a script at the address  http://localhost/php/global-variables/$_SERVER.php would be 127.0.0.1  
$_SERVER['SERVER_NAME' ] The name of the server host under which the current script is executing. If the script is running on a virtual host, this will be the value defined for that virtual host. Example: localhost  
$_SERVER['SERVER_SOFTWARE' ] Server identification string, given in the headers when responding to requests. Example: Apache/2.2.11 (Win32) PHP/5.3.0  
$_SERVER['SERVER_PROTOCOL' ] Name and revision of the information protocol via which the page was requested. Example: 'HTTP/1.0';    
$_SERVER['REQUEST_METHOD' ] Which request method was used to access the page. Example:  GET, POST.  
$_SERVER['REQUEST_TIME'] The timestamp of the start of the request. Available since PHP 5.1.0.  Its outputs is the same using time () function.  
$_SERVER['QUERY_STRING'] The query string, if any, via which the page was accessed. For instance, $_SERVER['QUERY_STRING'] in a script at the address  'http://localhost/php/global-variables/$_SERVER.php?txtvalue1=1&txtvalue2=2&btnsubmit=go' would be txtvalue1=1&txtvalue2=2&btnsubmit=go (It can work with method get).  
$_SERVER['DOCUMENT_ROOT'] The document root directory under which the current script is executing, as defined in the server's configuration file. Example: C: /wamp/www/  
$_SERVER['HTTP_ACCEPT'] Contents of the Accept: header from the current request, if there is one. Example: application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5  
$_SERVER['HTTP_ACCEPT_CHARSET'] Contents of the Accept-Charset: header from the current request, if there is one. Example: 'iso8859-1,*,utf-8'.  
$_SERVER['HTTP_ACCEPT_LANGUAGE'] 

Contents of the Accept-Language: header from the current request, if there is one. Example: enUS,en;q=0.8.  
$_SERVER['HTTP_CONNECTION'] Contents of the Connection: header from the current request, if there is one. Example: KeepAlive.  
$_SERVER['HTTP_HOST'] Contents of the Host: header from the current request, if there is one. Example: localhost  
$_SERVER['HTTP_REFERER'] The address of the page (if any) which referred the user agent to the current page. This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted. Example: http://localhost/www/php/global-variables/SERVER.php?txtvalue1=&txtvalue2=&btnsubmit=go  
$_SERVER['HTTP_USER_AGENT'] Contents of the User-Agent: header from the current request, if there is one. This is a string denoting the user agent being which is accessing the page. Example: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.7 (KHTML, like Gecko) Chrome/7.0.517.17 Safari/534.7.  
$_SERVER['REMOTE_ADDR'] The IP address from which the user is viewing the current page. Example: 127.0.0.1  
$_SERVER['REMOTE_PORT'] The port being used on the user's machine to communicate with the web server. Example: 1096  
$_SERVER['SCRIPT_FILENAME'] The absolute pathname of the currently executing script. Example: C:/wamp/www/php/globalvariables/$_SERVER.php  
$_SERVER['SERVER_PORT'] The port on the server machine being used by the web server for communication. For default setups, this will be '80'; using SSL, for instance, will change this to whatever your defined secure HTTP port is.  
$_SERVER['SERVER_PORT'] Contains the current script's path. This is useful for pages which need to point to themselves. Example: /php/global-variables/$_SERVER.php  
$_SERVER['REQUEST_URI'] The URI (Uniform Resource Identifier) which was given in order to access this page. Example:  /php/global-variables/$_SERVER.php?txtvalue1=1&txtvalue2=2&btnsubmit=go  

10.   Function testing on  variable  
- 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( value )   Returns 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_resource( value )  Returns true if value is a resource, false otherwise 
- is_null( value )  Returns true if value is null, false otherwise 
- isset ( $var [, $var [, $... ]] )  return true if a variable is set and is not NULL. If multiple parameters are supplied then isset() will return TRUE only if all of the parameters are set. Evaluation goes from left to right - empty( $var )   Returns true if a variable is empty or variable has value like: false, null, 0, “0”, “”, ‘’ and no set 
- unset( $var )   Unset a given variable 
- is_numeric($var)  Returns true if a variable contains a number or numeric string (strings containing a sign, numbers and decimal points). Example01:  <?php    $a = '';    $b = NULL;    isset($a); // => TRUE    isset($b); // => FALSE  ?> Example02:  <?php   $var = "+99.766";   if(is_numeric($var))   {    echo "true";   }   else   {    echo "false";   }   // returns true     $var = "b00";   if(is_numeric($var))   {    echo "true";   }   else   {    echo "false";   }    // returns false ?> 
11. Getting Variables from Form in PHP - In case: method="get" To return data from a HTML form element in case form has attribute method=”get”, you use the following syntax: 

$_GET ['formElement_name']; You can assign this to a variable: $Your_Variable = $_GET ['formElement_name'];  
- In case: method="post" To return data from a HTML form element in case form has attribute method=”post”, you use the following syntax: $_POST ['formElement_name']; You can assign this to a variable: $Your_Variable = $_POST ['formElement_name'];  
- In case: method="get" or method=”post” To return data from a HTML form element in case form has attribute method=”get” or method=”post”, you use the following syntax: $_REQUEST ['formElement_name']; You can assign this to a variable: $Your_Variable = $_ REQUEST ['formElement_name'];  
  Example:   <html> <head> <title>A BASIC HTML FORM</title>  <?php   $username = $_POST['username'];   print ($username);  ?> </head> <body>  <form action="test.php" method="post">   <input type="text" name="username" />   <input type="submit" name="btnsubmit" value="Submit" />  </form> </body> </html> Save and run your work, type any texts into the textbox and click the submit button to run your script. (Don't worry if you see an error message about "Undefined index". Click the button anyway.) You should see the text you input appear above your text box.  
12.  Import External PHP File You can insert the content of one PHP file into another PHP file before     the server executes it,   with the include() or require() function. The two functions are identical in every way, except how they handle errors: - include() generates a warning, but the script will continue execution - include_once() statement is identical to include() except PHP will check if the file has already been included, and if so, not include (require) it again. - require() generates a fatal error, and the script will stop - require_once() statement is identical to require() except PHP will check if the file has already been included, and if so, not include (require) it again. 

These two functions are used to create functions, headers, footers, or elements that will be reused on multiple pages.  
Server side includes saves a lot of work. This means that you can create a standard header, footer, or menu file for all your web pages. When the header needs to be updated, you can only update the include file, or when you add a new page to your site, you can simply change the menu file (instead of updating the links on all your web pages).  
  Error Example include() Function <html> <head><title>Import External PHP File</title>  <?php   include("wrongFile.php");   echo "Hello World!";  ?> </head> <body> </body> </html>  
Error message: Warning: include(wrongFile.php) [function.include]: failed to open stream: No such file or directory in C:\home\website\test.php on line 5  
Warning: include() [function.include]: Failed opening 'wrongFile.php' for inclusion (include_path='.;C:\php5\pear') in C:\home\website\test.php on line 5  
Hello World! Notice that the echo statement is executed! This is because a Warning does not stop the script execution.  
 Error Example require() Function <html> <head><title>Import External PHP File</title>  <?php   require("wrongFile.php");   echo "Hello World!";  ?> </head> <body> </body> </html>  
Error message: 

 Warning: require(wrongFile.php) [function.require]: failed to open stream: No such file or directory in C:\home\website\test.php on line 5  
Fatal error: require() [function.require]: Failed opening required 'wrongFile.php' (include_path='.;C:\php5\pear') in C:\home\website\test.php on line 5 The echo statement is not executed, because the script execution stopped after the fatal error. It is recommended to use the require() function instead of include(), because scripts should not continue after an error.  

Previous
Next Post »