Docstoc

v What is PHP - Wordpress Wordpress

Document Sample
v What is PHP - Wordpress Wordpress Powered By Docstoc
					SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR




  BCA 302:BUILDING APPLICATION
               USING ASP/PHP
                UNIT:-2 PHP




   AUTHOR: - LEC. JAVED KHAN .M. PATHAN
           CONTACT:-9998099262
         Email:-mcajaved@gmail.com
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS

                           UNIT:-2 PHP                                    17 MARKS




 What is PHP?
  PHP (recursive acronym for "PHP: Hypertext Preprocessor") is a widely-used Open
  Source general-purpose scripting language that is especially suited for Web development
  and can be embedded into HTML.
  Simple answer, but what does that mean? An example:
  Example 1.1. An introductory example
  <html>
      <head>
          <title>Example</title>
      </head>
      <body>

            <?php
            echo "Hi, I'm a PHP script!";
            ?>

      </body>
  </html>

  Notice how this is different from a script written in other languages like Perl or C --
  instead of writing a program with lots of commands to output HTML, you write an
  HTML script with some embedded code to do something (in this case, output some text).
  The PHP code is enclosed in special start and end tags that allow you to jump into and
  out of "PHP mode".
  What distinguishes PHP from something like client-side JavaScript is that the code is
  executed on the server. If you were to have a script similar to the above on your server,
  the client would receive the results of running that script, with no way of determining
  what the underlying code may be. You can even configure your web server to process all
  your HTML files with PHP, and then there's really no way that users can tell what you
  have up your sleeve.
  The best things in using PHP are that it is extremely simple for a newcomer, but offers
  many advanced features for a professional programmer. Don't be afraid reading the long
  list of PHP's features. You can jump in, in a short time, and start writing simple scripts in
  a few hours.
  Although PHP's development is focused on server-side scripting, you can do much more
  with it. Read on, and see more in the What can PHP do? section, or go right to the
  introductory tutorial if you are only interested in web programming.




Lecturer Javedkhan M. Pathan [9998099262]                                   Page 2 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS

What can PHP do?
    Anything. PHP is mainly focused on server-side scripting, so you can do anything any
    other CGI program can do, such as collect form data, generate dynamic page content, or
    send and receive cookies. But PHP can do much more.
    There are three main areas where PHP scripts are used.
       Server-side scripting. This is the most traditional and main target field for PHP. You
    need three things to make this work. The PHP parser (CGI or server module), a web
    server and a web browser. You need to run the web server, with a connected PHP
    installation. You can access the PHP program output with a web browser, viewing the
    PHP page through the server. All these can run on your home machine if you are just
    experimenting with PHP programming. See the installation instructions section for more
    information.
       Command line scripting. You can make a PHP script to run it without any server or
    browser. You only need the PHP parser to use it this way. This type of usage is ideal for
    scripts regularly executed using cron (on *nix or Linux) or Task Scheduler (on
    Windows). These scripts can also be used for simple text processing tasks. See the
    section about Command line usage of PHP for more information.
       Writing desktop applications. PHP is probably not the very best language to create a
    desktop application with a graphical user interface, but if you know PHP very well, and
    would like to use some advanced PHP features in your client-side applications you can
    also use PHP-GTK to write such programs. You also have the ability to write cross-
    platform applications this way. PHP-GTK is an extension to PHP, not available in the
    main distribution. If you are interested in PHP-GTK, visit » its own website.
    PHP can be used on all major operating systems, including Linux, many Unix variants
    (including HP-UX, Solaris and OpenBSD), Microsoft Windows, Mac OS X, RISC OS,
    and probably others. PHP has also support for most of the web servers today. This
    includes Apache, Microsoft Internet Information Server, Personal Web Server, Netscape
    and iPlanet servers, Oreilly Website Pro server, Caudium, Xitami, OmniHTTPd, and
    many others. For the majority of the servers PHP has a module, for the others supporting
    the CGI standard, PHP can work as a CGI processor.
    So with PHP, you have the freedom of choosing an operating system and a web server.
    Furthermore, you also have the choice of using procedural programming or object
    oriented programming, or a mixture of them. Although not every standard OOP feature
    is implemented in PHP 4, many code libraries and large applications (including the
    PEAR library) are written only using OOP code. PHP 5 fixes the OOP related
    weaknesses of PHP 4, and introduces a complete object model.
    With PHP you are not limited to output HTML. PHP's abilities includes outputting
    images, PDF files and even Flash movies (using libswf and Ming) generated on the fly.
    You can also output easily any text, such as XHTML and any other XML file. PHP can
    autogenerate these files, and save them in the file system, instead of printing it out,
    forming a server-side cache for your dynamic content.
    One of the strongest and most significant features in PHP is its support for a wide range
    of databases. Writing a database-enabled web page is incredibly simple. The following
    databases are currently supported:


Lecturer Javedkhan M. Pathan [9998099262]                                   Page 3 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
                 Adabas D                InterBase                       PostgreSQL
                 dBase                   FrontBase                       SQLite
                 Empress                 mSQL                            Solid
                 FilePro (read-only)     Direct MS-SQL                   Sybase
                 Hyperwave               MySQL                           Velocis
                 IBM DB2                 ODBC                            Unix dbm
                 Informix                Oracle (OCI7 and OCI8)
                 Ingres                  Ovrimos
  We also have a database abstraction extension (named PDO) allowing you to
  transparently use any database supported by that extension. Additionally PHP supports
  ODBC, the Open Database Connection standard, so you can connect to any other
  database supporting this world standard.
  PHP also has support for talking to other services using protocols such as LDAP, IMAP,
  SNMP, NNTP, POP3, HTTP, COM (on Windows) and countless others. You can also
  open raw network sockets and interact using any other protocol. PHP has support for the
  WDDX complex data exchange between virtually all Web programming languages.
  Talking about interconnection, PHP has support for instantiation of Java objects and
  using them transparently as PHP objects. You can also use our CORBA extension to
  access remote objects.
  PHP has extremely useful text processing features, from the POSIX Extended or Perl
  regular expressions to parsing XML documents. For parsing and accessing XML
  documents, PHP 4 supports the SAX and DOM standards, and you can also use the
  XSLT extension to transform XML documents. PHP 5 standardizes all the XML
  extensions on the solid base of libxml2 and extends the feature set adding SimpleXML
  and XMLReader support.
  At last but not least, we have many other interesting extensions, the mnoGoSearch
  search engine functions, the IRC Gateway functions, many compression utilities (gzip,
  bz2, zip), calendar conversion, translation...
  As you can see this page is not enough to list all the features and benefits PHP can offer.
  Read on in the sections about installing PHP, and see the function reference part for
  explanation of the extensions mentioned here.




 Variables:-
     1. Basics
     2. Predefined variables
     3. Variable scope

Lecturer Javedkhan M. Pathan [9998099262]                                  Page 4 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
      4. Variable variables
      5. Variables from outside PHP

1. Basics
   Variables in PHP are represented by a dollar sign followed by the name of the variable.
   The variable name is case-sensitive.
   Variable names follow the same rules as other labels in PHP. A valid variable name
   starts with a letter or underscore, followed by any number of letters, numbers, or
   underscores. As a regular expression, it would be expressed thus: '[a-zA-Z_\x7f-\xff][a-
   zA-Z0-9_\x7f-\xff]*'
   Note: For our purposes here, a letter is a-z, A-Z, and the ASCII characters from 127
   through 255 (0x7f-0xff).
   Note: $this is a special variable that can't be assigned.
   Tip
   You may also want to take a look at the Appendix T, Userland Naming Guide.
   For information on variable related functions, see the Variable Functions Reference.
   <?php
   $var = 'Bob';
   $Var = 'Joe';
   echo "$var, $Var";             // outputs "Bob, Joe"

   $4site = 'not yet';            // invalid; starts with a number
   $_4site = 'not yet';           // valid; starts with an underscore
   $täyte = 'mansikka';           // valid; 'ä' is (Extended) ASCII 228.
   ?>
   In PHP 3, variables are always assigned by value. That is to say, when you assign an
   expression to a variable, the entire value of the original expression is copied into the
   destination variable. This means, for instance, that after assigning one variable's value to
   another, changing one of those variables will have no effect on the other. For more
   information on this kind of assignment, see the chapter on Expressions.
   As of PHP 4, PHP offers another way to assign values to variables: assign by reference.
   This means that the new variable simply references (in other words, "becomes an alias
   for" or "points to") the original variable. Changes to the new variable affect the original,
   and vice versa.
   To assign by reference, simply prepend an ampersand (&) to the beginning of the
   variable which is being assigned (the source variable). For instance, the following code
   snippet outputs 'My name is Bob' twice:
   <?php
   $foo = 'Bob';                      // Assign the value 'Bob' to $foo
   $bar = &$foo;                      // Reference $foo via $bar.
   $bar = "My name is $bar";          // Alter $bar...
   echo $bar;
   echo $foo;                         // $foo is altered too.
   ?>
   One important thing to note is that only named variables may be assigned by reference.
   <?php
   $foo = 25;
   $bar = &$foo;           // This is a valid assignment.


Lecturer Javedkhan M. Pathan [9998099262]                                   Page 5 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
    $bar = &(24 * 7);       // Invalid; references an unnamed expression.

    function test()
    {
       return 25;
    }

    $bar = &test();         // Invalid.
    ?>
   It is not necessary to initialize variables in PHP however it is a very good practice.
   Uninitialized variables have a default value of their type - FALSE, zero, empty string or
   an empty array.
Example 12.1. Default values of uninitialized variables
    <?php
    echo ($unset_bool ? "true" : "false"); // false
    $unset_int += 25; // 0 + 25 => 25
    echo $unset_string . "abc"; // "" . "abc" => "abc"
    $unset_array[3] = "def"; // array() + array(3 => "def") => array(3 => "
    def")
    ?>

    Relying on the default value of an uninitialized variable is problematic in the case of
    including one file into another which uses the same variable name. It is also a major
    security risk with register_globals turned on. E_NOTICE level error is issued in case of
    working with uninitialized variables, however not in the case of appending elements to
    the uninitialized array. isset() language construct can be used to detect if a variable has
    been already initialized.

2. Predefined variables
   PHP provides a large number of predefined variables to any script which it runs. Many
   of these variables, however, cannot be fully documented as they are dependent upon
   which server is running, the version and setup of the server, and other factors. Some of
   these variables will not be available when PHP is run on the command line.
PHP Superglobals
   $GLOBALS
   Contains a reference to every variable which is currently available within the global
   scope of the script. The keys of this array are the names of the global variables.
   $GLOBALS has existed since PHP 3.
   $_SERVER
   Variables set by the web server or otherwise directly related to the execution
   environment of the current script. Analogous to the old $HTTP_SERVER_VARS array
   (which is still available, but deprecated).
   $_GET
   Variables provided to the script via URL query string. Analogous to the old
   $HTTP_GET_VARS array (which is still available, but deprecated).
   $_POST



Lecturer Javedkhan M. Pathan [9998099262]                                    Page 6 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
  Variables provided to the script via HTTP POST. Analogous to the old
  $HTTP_POST_VARS array (which is still available, but deprecated).
  $_COOKIE
  Variables provided to the script via HTTP cookies. Analogous to the old
  $HTTP_COOKIE_VARS array (which is still available, but deprecated).
  $_FILES
  Variables provided to the script via HTTP post file uploads. Analogous to the old
  $HTTP_POST_FILES array (which is still available, but deprecated). See POST method
  uploads for more information.
  $_ENV
  Variables provided to the script via the environment. Analogous to the old
  $HTTP_ENV_VARS array (which is still available, but deprecated).
  $_REQUEST
  Variables provided to the script via the GET, POST, and COOKIE input mechanisms,
  and which therefore cannot be trusted. The presence and order of variable inclusion in
  this array is defined according to the PHP variables_order configuration directive. This
  array has no direct analogue in versions of PHP prior to 4.1.0. See also
  import_request_variables().
  Caution
  Since PHP 4.3.0, FILE information from $_FILES does not exist in $_REQUEST.
  $_SESSION
  Variables which are currently registered to a script's session. Analogous to the old
  $HTTP_SESSION_VARS array (which is still available, but deprecated). See the Session
  handling functions section for more information.
3. 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:
  <?php
  $a = 1;
  include 'b.inc';
  ?>
  Here the $a variable will be available within the included b.inc script. However, 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

Lecturer Javedkhan M. Pathan [9998099262]                                 Page 7 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
    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 12.2. 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 12.3. Using $GLOBALS instead of global
    <?php
    $a = 1;
    $b = 2;

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

    Sum();
    echo $b;
    ?>

   The $GLOBALS array is an associative array with the name of the global variable being
   the key and the contents of that variable being the value of the array element. Notice
   how $GLOBALS exists in any scope, this is because $GLOBALS is a superglobal.
   Here's an example demonstrating the power of superglobals:
Example 12.4. Example demonstrating superglobals and scope
    <?php
    function test_global()


Lecturer Javedkhan M. Pathan [9998099262]                                      Page 8 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
    {
         // Most predefined variables aren't "super" and require
         // 'global' to be available to the functions local scope.
         global $HTTP_POST_VARS;

         echo $HTTP_POST_VARS['name'];

         // Superglobals are available in any scope and do
         // not require 'global'. Superglobals are available
         // as of PHP 4.1.0, and HTTP_POST_VARS is now
         // deemed deprecated.
         echo $_POST['name'];
    }
    ?>


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:
Example 12.5. Example demonstrating need for static variables
    <?php
    function Test()
    {
        $a = 0;
        echo $a;
        $a++;
    }
    ?>

   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:
Example 12.6. Example use of static variables
    <?php
    function Test()
    {
        static $a = 0;
        echo $a;
        $a++;
    }
    ?>

    Now, every time the Test() function is called it will print the value of $a and increment
    it.
    Static variables also provide one way to deal with recursive functions. A recursive
    function is one which calls itself. Care must be taken when writing a recursive function
    because it is possible to make it recurse indefinitely. You must make sure you have an



Lecturer Javedkhan M. Pathan [9998099262]                                    Page 9 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
   adequate way of terminating the recursion. The following simple function recursively
   counts to 10, using the static variable $count to know when to stop:
Example 12.7. Static variables with recursive functions
    <?php
    function Test()
    {
        static $count = 0;

         $count++;
         echo $count;
         if ($count < 10) {
             Test();
         }
         $count--;
    }
    ?>

   Note: Static variables may be declared as seen in the examples above. Trying to assign
   values to these variables which are the result of expressions will cause a parse error.
Example 12.8. Declaring static variables
    <?php
    function foo(){
        static $int = 0;                 // correct
        static $int = 1+2;               // wrong (as it is an expression)
        static $int = sqrt(121);         // wrong (as it is an expression too)

         $int++;
         echo $int;
    }
    ?>


References with global and static variables
    The Zend Engine 1, driving PHP 4, implements the static and global modifier for
    variables in terms of references. For example, a true global variable imported inside a
    function scope with the global statement actually creates a reference to the global
    variable. This can lead to unexpected behaviour which the following example addresses:
    <?php
    function test_global_ref() {
        global $obj;
        $obj = &new stdclass;
    }

    function test_global_noref() {
        global $obj;
        $obj = new stdclass;
    }

    test_global_ref();
    var_dump($obj);
    test_global_noref();



Lecturer Javedkhan M. Pathan [9998099262]                                 Page 10 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
  var_dump($obj);
  ?>
  Executing this example will result in the following output:
  NULL
  object(stdClass)(0) {
  }

  A similar behaviour applies to the static statement. References are not stored statically:
  <?php
  function &get_instance_ref() {
      static $obj;

       echo 'Static object: ';
       var_dump($obj);
       if (!isset($obj)) {
           // Assign a reference to the static variable
           $obj = &new stdclass;
       }
       $obj->property++;
       return $obj;
  }

  function &get_instance_noref() {
      static $obj;

       echo 'Static object: ';
       var_dump($obj);
       if (!isset($obj)) {
           // Assign the object to the static variable
           $obj = new stdclass;
       }
       $obj->property++;
       return $obj;
  }

  $obj1 = get_instance_ref();
  $still_obj1 = get_instance_ref();
  echo "\n";
  $obj2 = get_instance_noref();
  $still_obj2 = get_instance_noref();
  ?>
  Executing this example will result in the following output:
  Static object: NULL
  Static object: NULL

  Static object: NULL
  Static object: object(stdClass)(1) {
    ["property"]=>
    int(1)
  }

  This example demonstrates that when assigning a reference to a static variable, it's not
  remembered when you call the &get_instance_ref() function a second time.


Lecturer Javedkhan M. Pathan [9998099262]                                  Page 11 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS

4. 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.
  Warning
  Please note that variable variables cannot be used with PHP's Superglobal arrays within
  functions or class methods. The variable $this is also a special variable that cannot be
  referenced dynamically.


5. Variables from outside PHP
   HTML Forms (GET and POST)
  When a form is submitted to a PHP script, the information from that form is
  automatically made available to the script. There are many ways to access this
  information, for example:
  Example 12.9. A simple HTML form
  <form action="foo.php" method="post">
      Name: <input type="text" name="username" /><br />
      Email: <input type="text" name="email" /><br />
      <input type="submit" name="submit" value="Submit me!" />
  </form>



Lecturer Javedkhan M. Pathan [9998099262]                                  Page 12 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS


  Depending on your particular setup and personal preferences, there are many ways to
  access data from your HTML forms. Some examples are:
  Example 12.10. Accessing data from a simple POST HTML form
  <?php
  // Available since PHP 4.1.0

       echo $_POST['username'];
       echo $_REQUEST['username'];

       import_request_variables('p', 'p_');
       echo $p_username;

  // Available since PHP 3. As of PHP 5.0.0, these long predefined
  // variables can be disabled with the register_long_arrays directive.

       echo $HTTP_POST_VARS['username'];

  // Available if the PHP directive register_globals = on. As of
  // PHP 4.2.0 the default value of register_globals = off.
  // Using/relying on this method is not preferred.

       echo $username;
  ?>




  Using a GET form is similar except you'll use the appropriate GET predefined variable
  instead. GET also applies to the QUERY_STRING (the information after the '?' in a
  URL). So, for example, http://www.example.com/test.php?id=3 contains GET data
  which is accessible with $_GET['id']. See also $_REQUEST and
  import_request_variables().
  Note: Superglobal arrays, like $_POST and $_GET, became available in PHP 4.1.0
  As shown, before PHP 4.2.0 the default value for register_globals was on. And, in PHP
  3 it was always on. The PHP community is encouraging all to not rely on this directive
  as it's preferred to assume it's off and code accordingly.
  Note: The magic_quotes_gpc configuration directive affects Get, Post and Cookie
  values. If turned on, value (It's "PHP!") will automagically become (It\'s \"PHP!\").
  Escaping is needed for DB insertion. See also addslashes(), stripslashes() and
  magic_quotes_sybase.
  PHP also understands arrays in the context of form variables (see the related faq). You
  may, for example, group related variables together, or use this feature to retrieve values
  from a multiple select input. For example, let's post a form to itself and upon submission
  display the data:
  Example 12.11. More complex form variables
  <?php
  if ($_POST) {



Lecturer Javedkhan M. Pathan [9998099262]                                 Page 13 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
       echo '<pre>';
       echo htmlspecialchars(print_r($_POST, true));
       echo '</pre>';
  }
  ?>
  <form action="" method="post">
      Name: <input type="text" name="personal[name]" /><br />
      Email: <input type="text" name="personal[email]" /><br />
      Beer: <br />
      <select multiple name="beer[]">
          <option value="warthog">Warthog</option>
          <option value="guinness">Guinness</option>
          <option value="stuttgarter">Stuttgarter Schwabenbräu</option>
      </select><br />
      <input type="submit" value="submit me!" />
  </form>

  In PHP 3, the array form variable usage is limited to single-dimensional arrays. As of
  PHP 4, no such restriction applies.
  IMAGE SUBMIT variable names
  When submitting a form, it is possible to use an image instead of the standard submit
  button with a tag like:
  <input type="image" src="image.gif" name="sub" />


  When the user clicks somewhere on the image, the accompanying form will be
  transmitted to the server with two additional variables, sub_x and sub_y. These contain
  the coordinates of the user click within the image. The experienced may note that the
  actual variable names sent by the browser contains a period rather than an underscore,
  but PHP converts the period to an underscore automatically.
  HTTP Cookies
  PHP transparently supports HTTP cookies as defined by » Netscape's Spec. Cookies are
  a mechanism for storing data in the remote browser and thus tracking or identifying
  return users. You can set cookies using the setcookie() function. Cookies are part of the
  HTTP header, so the SetCookie function must be called before any output is sent to the
  browser. This is the same restriction as for the header() function. Cookie data is then
  available in the appropriate cookie data arrays, such as $_COOKIE,
  $HTTP_COOKIE_VARS as well as in $_REQUEST. See the setcookie() manual page for
  more details and examples.
  If you wish to assign multiple values to a single cookie variable, you may assign it as an
  array. For example:
  <?php
     setcookie("MyCookie[foo]", 'Testing 1', time()+3600);
     setcookie("MyCookie[bar]", 'Testing 2', time()+3600);
  ?>




Lecturer Javedkhan M. Pathan [9998099262]                                Page 14 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
  That will create two separate cookies although MyCookie will now be a single array in
  your script. If you want to set just one cookie with multiple values, consider using
  serialize() or explode() on the value first.
  Note that a cookie will replace a previous cookie by the same name in your browser
  unless the path or domain is different. So, for a shopping cart application you may want
  to keep a counter and pass this along. i.e.
  Example 12.12. A setcookie() example
  <?php
  if (isset($_COOKIE['count'])) {
      $count = $_COOKIE['count'] + 1;
  } else {
      $count = 1;
  }
  setcookie('count', $count, time()+3600);
  setcookie("Cart[$count]", $item, time()+3600);
  ?>


  Dots in incoming variable names
  Typically, PHP does not alter the names of variables when they are passed into a script.
  However, it should be noted that the dot (period, full stop) is not a valid character in a
  PHP variable name. For the reason, look at it: <?php
  $varname.ext; /* invalid variable name */
  ?> Now, what the parser sees is a variable named $varname,      followed by the string
  concatenation operator, followed by the barestring (i.e. unquoted string which doesn't
  match any known key or reserved words) 'ext'. Obviously, this doesn't have the intended
  result.
  For this reason, it is important to note that PHP will automatically replace any dots in
  incoming variable names with underscores.
  Determining variable types
  Because PHP determines the types of variables and converts them (generally) as needed,
  it is not always obvious what type a given variable is at any one time. PHP includes
  several functions which find out what type a variable is, such as: gettype(), is_array(),
  is_float(), is_int(), is_object(), and is_string(). See also the chapter on Types.




 Operators:-
Lecturer Javedkhan M. Pathan [9998099262]                                  Page 15 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
  1. Operator Precedence
  2. Arithmetic Operators
  3. Assignment Operators
  4. Bitwise Operators
  5. Comparison Operators
  6. Error Control Operators
  7. Execution Operators
  8. Incrementing/Decrementing Operators
  9. Logical Operators
  10. String Operators
  11. Array Operators
  12. Type Operators

  An operator is something that you feed with one or more values (or expressions, in
  programming jargon) which yields another value (so that the construction itself becomes
  an expression). So you can think of functions or constructions that return a value (like
  print) as operators and those that return nothing (like echo) as any other thing.
  There are three types of operators. Firstly there is the unary operator which operates on
  only one value, for example ! (the negation operator) or ++ (the increment operator). The
  second group are termed binary operators; this group contains most of the operators that
  PHP supports, and a list follows below in the section Operator Precedence.
  The third group is the ternary operator: ?:. It should be used to select between two
  expressions depending on a third one, rather than to select two sentences or paths of
  execution. Surrounding ternary expressions with parentheses is a very good idea.
1. Operator Precedence:-
  The precedence of an operator specifies how "tightly" it binds two expressions together.
  For example, in the expression 1 + 5 * 3, the answer is 16 and not 18 because the
  multiplication ("*") operator has a higher precedence than the addition ("+") operator.
  Parentheses may be used to force precedence, if necessary. For instance: (1 + 5) * 3
  evaluates to 18. If operator precedence is equal, left to right associativity is used.
  The following table lists the precedence of operators with the highest-precedence
  operators listed at the top of the table. Operators on the same line have equal precedence,
  in which case their associativity decides which order to evaluate them in.
  Table 15.1. Operator Precedence
                                                                              Additional
             Associativity                     Operators
                                                                             Information
            non-
                                   new                                 new
            associative
            left                   [                                   array()
            non-
                                   ++ --                               increment/decrement
            associative
            non-                   ~ - (int) (float) (string) (array)
                                                                       types
            associative            (object) @

Lecturer Javedkhan M. Pathan [9998099262]                                 Page 16 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
                                                                               Additional
            Associativity                  Operators
                                                                              Information
            non-
                                 instanceof                           types
            associative
            right                !                                    logical
            left                 */%                                  arithmetic
            left                 +-.                                  arithmetic and string
            left                 << >>                                bitwise
            non-
                                 < <= > >=                            comparison
            associative
            non-
                                 == != === !==                        comparison
            associative
            left                 &                                    bitwise and references
            left                 ^                                    bitwise
            left                 |                                    bitwise
            left                 &&                                   logical
            left                 ||                                   logical
            left                 ?:                                   ternary
                                 = += -= *= /= .= %= &= |= ^=
            right                                                     assignment
                                 <<= >>=
            left                 and                                  logical
            left                 xor                                  logical
            left                 or                                   logical
            left                 ,                                    many uses

  Left associativity means that the expression is evaluated from left to right, right
  associativity means the opposite.
  Example 15.1. Associativity
  <?php
  $a = 3 * 3 % 5; // (3 * 3) % 5 = 4
  $a = true ? 0 : true ? 1 : 2; // (true ? 0 : true) ? 1 : 2 = 2

  $a = 1;
  $b = 2;
  $a = $b += 3; // $a = ($b += 3) -> $a = 5, $b = 5
  ?>

  Use parentheses to increase readability of the code.




Lecturer Javedkhan M. Pathan [9998099262]                                     Page 17 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
  Note: Although = has a lower precedence than most other operators, PHP will still allow
  expressions similar to the following: if (!$a = foo()), in which case the return value of
  foo() is put into $a.
2. Arithmetic Operators:-
  Remember basic arithmetic from school? These work just like those.
                  Table 15.2. 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.

  The division operator ("/") returns a float value unless the two operands are integers (or
  strings that get converted to integers) and the numbers are evenly divisible, in which
  case an integer value will be returned.
  Operands of modulus are converted to integers (by stripping the decimal part) before
  processing.
  Note: Remainder $a % $b is negative for negative $a.
  See also the manual page on Math functions.
3. 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").
  The value of an assignment expression is the value assigned. That is, the value of "$a =
  3" is 3. This allows you to do some tricky things:
  <?php

  $a = ($b = 4) + 5; // $a is equal to 9 now, and $b has been set to 4.

  ?>
  In addition to the basic assignment operator, there are "combined operators" for all of the
  binary arithmetic, array union and string operators that allow you to use a value in an
  expression and then set its value to the result of that expression. For example:
  <?php

  $a = 3;
  $a += 5; // sets $a to 8, as if we had said: $a = $a + 5;
  $b = "Hello ";
  $b .= "There!"; // sets $b to "Hello There!", just like $b = $b . "Ther
  e!";

  ?>


Lecturer Javedkhan M. Pathan [9998099262]                                  Page 18 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
  Note that the assignment copies the original variable to the new one (assignment by
  value), so changes to one will not affect the other. This may also have relevance if you
  need to copy something like a large array inside a tight loop. Since PHP 4, assignment
  by reference has been supported, using the $var = &$othervar; syntax, but this is not
  possible in PHP 3. 'Assignment by reference' means that both variables end up pointing
  at the same data, and nothing is copied anywhere. To learn more about references, please
  read References explained. As of PHP 5, objects are assigned by reference unless
  explicitly told otherwise with the new clone keyword.
4. Bitwise Operators:-
  Bitwise operators allow you to turn specific bits within an integer on or off. If both the
  left- and right-hand parameters are strings, the bitwise operator will operate on the
  characters' ASCII values.
  <?php
  echo 12 ^ 9; // Outputs '5'

  echo "12" ^ "9"; // Outputs the Backspace character (ascii 8)
                   // ('1' (ascii 49)) ^ ('9' (ascii 57)) = #8

  echo "hallo" ^ "hello"; // Outputs the ascii values #0 #4 #0 #0 #0
                          // 'a' ^ 'e' = #4
  ?>
  Table 15.3. Bitwise Operators
  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.
                                 Shift the bits of $a $b steps to the left (each step means
  $a << $b       Shift left
                                 "multiply by two")
                 Shift           Shift the bits of $a $b steps to the right (each step means
  $a >> $b
                 right           "divide by two")

  Warning
  Don't right shift for more than 32 bits on 32 bits systems. Don't left shift in case it results
  to number longer than 32 bits.
5. Comparison Operators:-
  Comparison operators, as their name implies, allow you to compare two values. You
  may also be interested in viewing the type comparison tables, as they show examples of
  various type related comparisons.
  Table 15.4. Comparison Operators
  Example              Name                                  Result
  $a == $b        Equal                   TRUE   if $a is equal to $b.


Lecturer Javedkhan M. Pathan [9998099262]                                        Page 19 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS

   Example              Name                                     Result
  $a ===                                TRUE  if $a is equal to $b, and they are of the same
                   Identical
  $b                                    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.
                                        TRUE if $a is not equal to $b, or they are not of the
  $a !== $b        Not identical
                                        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.
                   Less than or
  $a <= $b                              TRUE   if $a is less than or equal to $b.
                   equal to
                   Greater than or
  $a >= $b                              TRUE   if $a is greater than or equal to $b.
                   equal to

  If you compare an integer with a string, the string is converted to a number. If you
  compare two numerical strings, they are compared as integers. These rules also apply to
  the switch statement.
  <?php
  var_dump(0 == "a"); // 0 == 0 -> true
  var_dump("1" == "01"); // 1 == 1 -> true
  var_dump("1" == "1e0"); // 1 == 1 -> true

  switch ("a") {
  case 0:
      echo "0";
      break;
  case "a": // never reached because "a" is already matched with 0
      echo "a";
      break;
  }
  ?>
  For various types, comparison is done according to the following table (in order).




  Table 15.5. Comparison with Various Types
    Type of         Type of
                                                                 Result
   Operand 1       Operand 2
                                       Convert NULL to "", numerical or lexical
  null or string      string
                                       comparison
  bool or null        anything         Convert to bool, FALSE < TRUE



Lecturer Javedkhan M. Pathan [9998099262]                                        Page 20 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS

    Type of            Type of
                                                               Result
   Operand 1          Operand 2
                                        Built-in classes can define its own comparison,
                                        different classes are uncomparable, same class -
  object             object
                                        compare properties the same way as arrays (PHP
                                        4), PHP 5 has its own explanation
  string,            string,
                                        Translate strings and resources to numbers, usual
  resource or        resource or
                                        math
  number             number
                                        Array with fewer members is smaller, if key from
                                        operand 1 is not found in operand 2 then arrays are
  array              array
                                        uncomparable, otherwise - compare value by value
                                        (see following example)
  array              anything           array is always greater
  object             anything           object is always greater

  Example 15.2. Transcription of standard array comparison
  <?php
  // Arrays are compared like this with standard comparison operators
  function standard_array_compare($op1, $op2)
  {
      if (count($op1) < count($op2)) {
          return -1; // $op1 < $op2
      } elseif (count($op1) > count($op2)) {
          return 1; // $op1 > $op2
      }
      foreach ($op1 as $key => $val) {
          if (!array_key_exists($key, $op2)) {
              return null; // uncomparable
          } elseif ($val < $op2[$key]) {
              return -1;
          } elseif ($val > $op2[$key]) {
              return 1;
          }
      }
      return 0; // $op1 == $op2
  }
  ?>

  See also strcasecmp(), strcmp(), Array operators, and the manual section on Types.
  Ternary Operator
  Another conditional operator is the "?:" (or ternary) operator.
  Example 15.3. Assigning a default value
  <?php
  // Example usage for: Ternary Operator
  $action = (empty($_POST['action'])) ? 'default' : $_POST['action'];



Lecturer Javedkhan M. Pathan [9998099262]                                Page 21 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS

  // The above is identical to this if/else statement
  if (empty($_POST['action'])) {
      $action = 'default';
  } else {
      $action = $_POST['action'];
  }

  ?>

  The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to
  TRUE, and expr3 if expr1 evaluates to FALSE.
  Note: Please note that the ternary operator is a statement, and that it doesn't evaluate to a
  variable, but to the result of a statement. This is important to know if you want to return
  a variable by reference. The statement return $var == 42 ? $a : $b; in a return-by-
  reference function will therefore not work and a warning is issued in later PHP versions.
  Note: Is is recommended that you avoid "stacking" ternary expressions. PHP's behaviour
  when using more than one ternary operator within a single statement is non-obvious:
  Example 15.4. Non-obvious Ternary Behaviour
  <?php
  // on first glance, the following appears to output 'true'
  echo (true?'true':false?'t':'f');

  // however, the actual output of the above is 't'
  // this is because ternary expressions are evaluated from left to right

  // the following is a more obvious version of the same code as above
  echo ((true ? 'true' : 'false') ? 't' : 'f');

  // here, you can see that the first expression is evaluated to 'true',
  which
  // in turn evaluates to (bool)true, thus returning the true branch of t
  he
  // second ternary expression.
  ?>
6. 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.


Lecturer Javedkhan M. Pathan [9998099262]                                   Page 22 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS

  ?>
  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.
  See also error_reporting() and the manual section for Error Handling and Logging
  functions.
  Warning
  Currently the "@" error-control operator prefix will even disable error reporting for
  critical errors that will terminate script execution. Among other things, this means that if
  you use "@" to suppress errors from a certain function and either it isn't available or has
  been mistyped, the script will die right there with no indication as to why.
7. Execution Operators:-
  PHP supports one execution operator: backticks (``). Note that these are not single-
  quotes! PHP will attempt to execute the contents of the backticks as a shell command;
  the output will be returned (i.e., it won't simply be dumped to output; it can be assigned
  to a variable). Use of the backtick operator is identical to shell_exec().
  <?php
  $output = `ls -al`;
  echo "<pre>$output</pre>";
  ?>
  Note: The backtick operator is disabled when safe mode is enabled or shell_exec() is
  disabled
8. Incrementing/Decrementing Operators:-
  PHP supports C-style pre- and post-increment and decrement operators.
  Note: The increment/decrement operators do not affect boolean values. Decrementing
  NULL values has no effect too, but incrementing them results in 1.
  Table 15.6. Increment/decrement Operators
  Example            Name                             Effect
  ++$a           Pre-increment         Increments $a by one, then returns $a.
  $a++           Post-increment        Returns $a, then increments $a by one.
  --$a           Pre-decrement         Decrements $a by one, then returns $a.
  $a--           Post-decrement        Returns $a, then decrements $a by one.

  Here's a simple example script:
  <?php
  echo "<h3>Postincrement</h3>";
  $a = 5;
  echo "Should be 5: " . $a++ . "<br />\n";
  echo "Should be 6: " . $a . "<br />\n";

  echo "<h3>Preincrement</h3>";


Lecturer Javedkhan M. Pathan [9998099262]                                  Page 23 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
  $a = 5;
  echo "Should be 6: " . ++$a . "<br />\n";
  echo "Should be 6: " . $a . "<br />\n";

  echo   "<h3>Postdecrement</h3>";
  $a =   5;
  echo   "Should be 5: " . $a-- . "<br />\n";
  echo   "Should be 4: " . $a . "<br />\n";

  echo   "<h3>Predecrement</h3>";
  $a =   5;
  echo   "Should be 4: " . --$a . "<br />\n";
  echo   "Should be 4: " . $a . "<br />\n";
  ?>
  PHP follows Perl's convention when dealing with arithmetic operations on character
  variables and not C's. For example, in Perl 'Z'+1 turns into 'AA', while in C 'Z'+1 turns
  into '[' ( ord('Z') == 90, ord('[') == 91 ). Note that character variables can be incremented
  but not decremented and even so only plain ASCII characters (a-z and A-Z) are
  supported.
  Example 15.5. Arithmetic Operations on Character Variables
  <?php
  $i = 'W';
  for ($n=0; $n<6; $n++) {
      echo ++$i . "\n";
  }
  ?>
  The above example will output:
  X
  Y
  Z
  AA
  AB
  AC




  Incrementing or decrementing booleans has no effect.
9. Logical Operators:-
  Table 15.7. 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.


Lecturer Javedkhan M. Pathan [9998099262]                                    Page 24 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS

   Example        Name                            Result
  $a || $b        Or          TRUE   if either $a or $b is TRUE.

  The reason for the two different variations of "and" and "or" operators is that they
  operate at different precedences. (See Operator Precedence.)
  Example 15.6. Logical operators illustrated
  <?php

  //   foo() will never get called as those operators are short-circuit
  $a   = (false && foo());
  $b   = (true || foo());
  $c   = (false and foo());
  $d   = (true or foo());

  // "||" has a greater precedence than "or"
  $e = false || true; // $e will be assigned to (false || true) which is
  true
  $f = false or true; // $f will be assigned to false
  var_dump($e, $f);

  // "&&" has a greater precedence than "and"
  $g = true && false; // $g will be assigned to (true && false) which is
  false
  $h = true and false; // $h will be assigned to true
  var_dump($g, $h);
  ?>
  The above example will output something similar to:
  bool(true)
  bool(false)
  bool(false)
  bool(true)
10.     String Operators:-
  There are two string operators. The first is the concatenation operator ('.'), which returns
  the concatenation of its right and left arguments. The second is the concatenating
  assignment operator ('.='), which appends the argument on the right side to the argument
  on the left side. Please read Assignment Operators for more information.
  <?php
  $a = "Hello ";
  $b = $a . "World!"; // now $b contains "Hello World!"

  $a = "Hello ";
  $a .= "World!";           // now $a contains "Hello World!"
  ?>
11. Array Operators:-
  Table 15.8. Array Operators
  Example         Name                                         Result
  $a + $b         Union              Union of $a and $b.

Lecturer Javedkhan M. Pathan [9998099262]                                  Page 25 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS

   Example         Name                                       Result
  $a == $b       Equality         TRUE   if $a and $b have the same key/value pairs.
  $a ===                          TRUE if $a and $b have the same key/value pairs in the
                 Identity
  $b                              same order and of the same types.
  $a != $b       Inequality       TRUE   if $a is not equal to $b.
  $a <> $b       Inequality       TRUE   if $a is not equal to $b.
                 Non-
  $a !== $b                       TRUE   if $a is not identical to $b.
                 identity

  The + operator appends elements of remaining keys from the right handed array to the
  left handed, whereas duplicated keys are NOT overwritten.
  <?php
  $a = array("a" => "apple", "b" => "banana");
  $b = array("a" => "pear", "b" => "strawberry", "c" => "cherry");

  $c = $a + $b; // Union of $a and $b
  echo "Union of \$a and \$b: \n";
  var_dump($c);

  $c = $b + $a; // Union of $b and $a
  echo "Union of \$b and \$a: \n";
  var_dump($c);
  ?>
  When executed, this script will print the following: Union of $a and $b:
  array(3) {
    ["a"]=>
    string(5) "apple"
    ["b"]=>
    string(6) "banana"
    ["c"]=>
    string(6) "cherry"
  }
  Union of $b and $a:
  array(3) {
    ["a"]=>
    string(4) "pear"
    ["b"]=>
    string(10) "strawberry"
    ["c"]=>
    string(6) "cherry"
  }
  Elements of arrays are equal for the comparison if they have the same key and value.
  Example 15.7. Comparing arrays
  <?php
  $a = array("apple", "banana");
  $b = array(1 => "banana", "0" => "apple");

  var_dump($a == $b); // bool(true)



Lecturer Javedkhan M. Pathan [9998099262]                                Page 26 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
  var_dump($a === $b); // bool(false)
  ?>


12. Type Operators:-
  instanceof is used to determine whether a PHP variable is an instantiated object of a
  certain class:
  Example 15.8. Using instanceof with classes
  <?php
  class MyClass
  {
  }
  class NotMyClass
  {
  }
  $a = new MyClass;

  var_dump($a instanceof MyClass);
  var_dump($a instanceof NotMyClass);
  ?>
  The above example will output:
  bool(true)
  bool(false)




  instanceof can also be used to determine whether a variable is an instantiated object of a
  class that inherits from a parent class:
  Example 15.9. Using instanceof with inherited classes
  <?php
  class ParentClass
  {
  }
  class MyClass extends ParentClass
  {
  }
  $a = new MyClass;

  var_dump($a instanceof MyClass);
  var_dump($a instanceof ParentClass);
  ?>
  The above example will output:
  bool(true)
  bool(true)




  Lastly, instanceof can also be used to determine whether a variable is an instantiated
  object of a class that implements an interface:


Lecturer Javedkhan M. Pathan [9998099262]                                 Page 27 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
  Example 15.10. Using instanceof for class
  <?php
  interface MyInterface
  {
  }
  class MyClass implements MyInterface
  {
  }
  $a = new MyClass;

  var_dump($a instanceof MyClass);
  var_dump($a instanceof MyInterface);
  ?>
  The above example will output:
  bool(true)
  bool(true)




  Although instanceof is usually used with a literal classname, it can also be used with
  another object or a string variable:
  Example 15.11. Using instanceof with other variables
  <?php
  interface MyInterface
  {
  }
  class MyClass implements MyInterface
  {
  }
  $a = new MyClass;
  $b = new MyClass;
  $c = 'MyClass';
  $d = 'NotMyClass';
  var_dump($a instanceof $b); // $b is an object of class MyClass
  var_dump($a instanceof $c); // $c is a string 'MyClass'
  var_dump($a instanceof $d); // $d is a string 'NotMyClass'
  ?>
  The above example will output:
  bool(true)
  bool(true)
  bool(false)




  There are a few pitfalls to be aware of. Before PHP version 5.1.0, instanceof would call
  __autoload() if the class name did not exist. In addition, if the class was not loaded, a
  fatal error would occur. This can be worked around by using a dynamic class reference,
  or a string variable containing the class name:



Lecturer Javedkhan M. Pathan [9998099262]                                 Page 28 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
     Example 15.12. Avoiding classname lookups and fatal errors with instanceof in
     PHP 5.0
     <?php
     $d = 'NotMyClass';
     var_dump($a instanceof $d); // no fatal error here
     ?>
     The above example will output:
     bool(false)


 Conditional structure and looping structure:-
     Introduction                                  break
     if                                            continue
     else                                          switch
     elseif                                        declare
     Alternative syntax for control structures     return
     while                                         require
     do-while                                      include
     for                                           require_once
     foreach                                       include_once



Introduction
     Any PHP script is built out of a series of statements. A statement can be an assignment, a
     function call, a loop, a conditional statement or even a statement that does nothing (an
     empty statement). Statements usually end with a semicolon. In addition, statements can
     be grouped into a statement-group by encapsulating a group of statements with curly
     braces. A statement-group is a statement by itself as well. The various statement types
     are described in this chapter.


if
     The if construct is one of the most important features of many languages, PHP included.
     It allows for conditional execution of code fragments. PHP features an if structure that is
     similar to that of C:
     if (expr)
         statement


     As described in the section about expressions, expression is evaluated to its Boolean
     value. If expression evaluates to TRUE, PHP will execute statement, and if it evaluates
     to FALSE - it'll ignore it. More information about what values evaluate to FALSE can be
     found in the 'Converting to boolean' section.

Lecturer Javedkhan M. Pathan [9998099262]                                     Page 29 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
   The following example would display a is bigger than b if $a is bigger than $b:
   <?php
   if ($a > $b)
       echo "a is bigger than b";
   ?>
   Often you'd want to have more than one statement to be executed conditionally. Of
   course, there's no need to wrap each statement with an if clause. Instead, you can group
   several statements into a statement group. For example, this code would display a is
   bigger than b if $a is bigger than $b, and would then assign the value of $a into $b:
   <?php
   if ($a > $b) {
       echo "a is bigger than b";
       $b = $a;
   }
   ?>
   If statements can be nested indefinitely within other if statements, which provides you
   with complete flexibility for conditional execution of the various parts of your program.
else
   Often you'd want to execute a statement if a certain condition is met, and a different
   statement if the condition is not met. This is what else is for. else extends an if statement
   to execute a statement in case the expression in the if statement evaluates to FALSE. For
   example, the following code would display a is bigger than b if $a is bigger than
   $b, and a is NOT bigger than b otherwise:
   <?php
   if ($a > $b) {
       echo "a is bigger than b";
   } else {
       echo "a is NOT bigger than b";
   }
   ?>
   The else statement is only executed if the if expression evaluated to FALSE, and if there
   were any elseif expressions - only if they evaluated to FALSE as well (see elseif).
elseif
   elseif, as its name suggests, is a combination of if and else. Like else, it extends an if
   statement to execute a different statement in case the original if expression evaluates to
   FALSE. However, unlike else, it will execute that alternative expression only if the elseif
   conditional expression evaluates to TRUE. For example, the following code would display
   a is bigger than b, a equal to b or a is smaller than b:
   <?php
   if ($a >   $b) {
       echo   "a is bigger than b";
   } elseif   ($a == $b) {
       echo   "a is equal to b";
   } else {
       echo   "a is smaller than b";
   }
   ?>




Lecturer Javedkhan M. Pathan [9998099262]                                    Page 30 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
   There may be several elseifs within the same if statement. The first elseif expression (if
   any) that evaluates to TRUE would be executed. In PHP, you can also write 'else if' (in
   two words) and the behavior would be identical to the one of 'elseif' (in a single word).
   The syntactic meaning is slightly different (if you're familiar with C, this is the same
   behavior) but the bottom line is that both would result in exactly the same behavior.
   The elseif statement is only executed if the preceding if expression and any preceding
   elseif expressions evaluated to FALSE, and the current elseif expression evaluated to
   TRUE.
Alternative syntax for control structures
   PHP offers an alternative syntax for some of its control structures; namely, if, while, for,
   foreach, and switch. In each case, the basic form of the alternate syntax is to change the
   opening brace to a colon (:) and the closing brace to endif;, endwhile;, endfor;,
   endforeach;, or endswitch;, respectively.
   <?php if ($a == 5): ?>
   A is equal to 5
   <?php endif; ?>
   In the above example, the HTML block "A is equal to 5" is nested within an if statement
   written in the alternative syntax. The HTML block would be displayed only if $a is
   equal to 5.
   The alternative syntax applies to else and elseif as well. The following is an if structure
   with elseif and else in the alternative format:
   <?php
   if ($a == 5):
       echo "a equals 5";
       echo "...";
   elseif ($a == 6):
       echo "a equals 6";
       echo "!!!";
   else:
       echo "a is neither 5 nor 6";
   endif;
   ?>
   See also while, for, and if for further examples.
while
   while loops are the simplest type of loop in PHP. They behave just like their C
   counterparts. The basic form of a while statement is:
   while (expr)
       statement


   The meaning of a while statement is simple. It tells PHP to execute the nested
   statement(s) repeatedly, as long as the while expression evaluates to TRUE. The value of
   the expression is checked each time at the beginning of the loop, so even if this value
   changes during the execution of the nested statement(s), execution will not stop until the
   end of the iteration (each time PHP runs the statements in the loop is one iteration).



Lecturer Javedkhan M. Pathan [9998099262]                                    Page 31 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
  Sometimes, if the while expression evaluates to FALSE from the very beginning, the
  nested statement(s) won't even be run once.
  Like with the if statement, you can group multiple statements within the same while loop
  by surrounding a group of statements with curly braces, or by using the alternate syntax:
  while (expr):
      statement
      ...
  endwhile;


  The following examples are identical, and both print the numbers 1 through 10:
  <?php
  /* example 1 */

  $i = 1;
  while ($i <= 10) {
      echo $i++; /* the printed value would be
                     $i before the increment
                     (post-increment) */
  }

  /* example 2 */

  $i = 1;
  while ($i <= 10):
      echo $i;
      $i++;
  endwhile;
  ?>
do-while
  do-while loops are very similar to while loops, except the truth expression is checked at
  the end of each iteration instead of in the beginning. The main difference from regular
  while loops is that the first iteration of a do-while loop is guaranteed to run (the truth
  expression is only checked at the end of the iteration), whereas it's may not necessarily
  run with a regular while loop (the truth expression is checked at the beginning of each
  iteration, if it evaluates to FALSE right from the beginning, the loop execution would end
  immediately).
  There is just one syntax for do-while loops:
  <?php
  $i = 0;
  do {
       echo $i;
  } while ($i > 0);
  ?>
  The above loop would run one time exactly, since after the first iteration, when truth
  expression is checked, it evaluates to FALSE ($i is not bigger than 0) and the loop
  execution ends.




Lecturer Javedkhan M. Pathan [9998099262]                                 Page 32 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
  Advanced C users may be familiar with a different usage of the do-while loop, to allow
  stopping execution in the middle of code blocks, by encapsulating them with do-while
  (0), and using the break statement. The following code fragment demonstrates this:
  <?php
  do {
       if ($i < 5) {
           echo "i is not big enough";
           break;
       }
       $i *= $factor;
       if ($i < $minimum_limit) {
           break;
       }
     echo "i is ok";

       /* process i */

  } while (0);
  ?>
for
  for loops are the most complex loops in PHP. They behave like their C counterparts. The
  syntax of a for loop is:
  for (expr1; expr2; expr3)
      statement


  The first expression (expr1) is evaluated (executed) once unconditionally at the
  beginning of the loop.
  In the beginning of each iteration, expr2 is evaluated. If it evaluates to TRUE, the loop
  continues and the nested statement(s) are executed. If it evaluates to FALSE, the
  execution of the loop ends.
  At the end of each iteration, expr3 is evaluated (executed).
  Each of the expressions can be empty or contain multiple expressions separated by
  commas. In expr2, all expressions separated by a comma are evaluated but the result is
  taken from the last part. expr2 being empty means the loop should be run indefinitely
  (PHP implicitly considers it as TRUE, like C). This may not be as useless as you might
  think, since often you'd want to end the loop using a conditional break statement instead
  of using the for truth expression.
  Consider the following examples. All of them display the numbers 1 through 10:
  <?php
  /* example 1 */

  for ($i = 1; $i <= 10; $i++) {
      echo $i;
  }

  /* example 2 */

  for ($i = 1; ; $i++) {


Lecturer Javedkhan M. Pathan [9998099262]                                Page 33 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
       if ($i > 10) {
           break;
       }
       echo $i;
  }

  /* example 3 */

  $i = 1;
  for (; ; ) {
      if ($i > 10) {
          break;
      }
      echo $i;
      $i++;
  }

  /* example 4 */

  for ($i = 1, $j = 0; $i <= 10; $j += $i, print $i, $i++);
  ?>
  Of course, the first example appears to be the nicest one (or perhaps the fourth), but you
  may find that being able to use empty expressions in for loops comes in handy in many
  occasions.
  PHP also supports the alternate "colon syntax" for for loops.
  for (expr1; expr2; expr3):
      statement
      ...
  endfor;
foreach
  PHP 4 introduced a foreach construct, much like Perl and some other languages. 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. There are two syntaxes; the second is a minor but useful extension
  of the first:
  foreach (array_expression as $value)
      statement
  foreach (array_expression as $key => $value)
      statement


  The first form loops over the array given by array_expression. On each loop, the value
  of the current element is assigned to $value and the internal array pointer is advanced by
  one (so on the next loop, you'll be looking at the next element).
  The second form does the same thing, except that the current element's key will be
  assigned to the variable $key on each loop.
  As of PHP 5, it is possible to iterate objects too.



Lecturer Javedkhan M. Pathan [9998099262]                                 Page 34 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
  Note: When foreach first starts executing, the internal array pointer is automatically
  reset to the first element of the array. This means that you do not need to call reset()
  before a foreach loop.
  Note: Unless the array is referenced, foreach operates on a copy of the specified array
  and not the array itself. foreach has some side effects on the array pointer. Don't rely on
  the array pointer during or after the foreach without resetting it.
  As of PHP 5, you can easily modify array's elements by preceding $value with &. This
  will assign reference instead of copying the value.
  <?php
  $arr = array(1, 2, 3, 4);
  foreach ($arr as &$value) {
      $value = $value * 2;
  }
  // $arr is now array(2, 4, 6, 8)
  unset($value); // break the reference with the last element
  ?>
  This is possible only if iterated array can be referenced (i.e. is variable).
  Warning
  Reference of a $value and the last array element remain even after the foreach loop. It is
  recommended to destroy it by unset().
  Note: foreach does not support the ability to suppress error messages using '@'.
  You may have noticed that the following are functionally identical:
  <?php
  $arr = array("one", "two", "three");
  reset($arr);
  while (list(, $value) = each($arr)) {
      echo "Value: $value<br />\n";
  }

  foreach ($arr as $value) {
      echo "Value: $value<br />\n";
  }
  ?>
  The following are also functionally identical:
  <?php
  $arr = array("one", "two", "three");
  reset($arr);
  while (list($key, $value) = each($arr)) {
      echo "Key: $key; Value: $value<br />\n";
  }

  foreach ($arr as $key => $value) {
      echo "Key: $key; Value: $value<br />\n";
  }
  ?>
  Some more examples to demonstrate usages:
  <?php
  /* foreach example 1: value only */

  $a = array(1, 2, 3, 17);



Lecturer Javedkhan M. Pathan [9998099262]                                  Page 35 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
  foreach ($a as $v) {
     echo "Current value of \$a: $v.\n";
  }

  /* foreach example 2: value (with key printed for illustration) */

  $a = array(1, 2, 3, 17);

  $i = 0; /* for illustrative purposes only */

  foreach ($a as $v) {
      echo "\$a[$i] => $v.\n";
      $i++;
  }

  /* foreach example 3: key and value */

  $a = array(
      "one" => 1,
      "two" => 2,
      "three" => 3,
      "seventeen" => 17
  );

  foreach ($a as $k => $v) {
      echo "\$a[$k] => $v.\n";
  }

  /* foreach example 4: multi-dimensional arrays */
  $a = array();
  $a[0][0] = "a";
  $a[0][1] = "b";
  $a[1][0] = "y";
  $a[1][1] = "z";

  foreach ($a as $v1) {
      foreach ($v1 as $v2) {
          echo "$v2\n";
      }
  }

  /* foreach example 5: dynamic arrays */

  foreach (array(1, 2, 3, 4, 5) as $v) {
      echo "$v\n";
  }
  ?>
break
  break ends execution of the current for, foreach, while, do-while or switch structure.
  break accepts an optional numeric argument which tells it how many nested enclosing
  structures are to be broken out of.
  <?php
  $arr = array('one', 'two', 'three', 'four', 'stop', 'five');


Lecturer Javedkhan M. Pathan [9998099262]                               Page 36 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
  while (list(, $val) = each($arr)) {
      if ($val == 'stop') {
          break;    /* You could also write 'break 1;' here. */
      }
      echo "$val<br />\n";
  }

  /* Using the optional argument. */

  $i = 0;
  while (++$i) {
      switch ($i) {
      case 5:
          echo "At 5<br />\n";
          break 1; /* Exit only the switch. */
      case 10:
          echo "At 10; quitting<br />\n";
          break 2; /* Exit the switch and the while. */
      default:
          break;
      }
  }
  ?>
continue
  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.
  Note: Note that in PHP the switch statement is considered a looping structure for the
  purposes of continue.
  continue accepts an optional numeric argument which tells it how many levels of
  enclosing loops it should skip to the end of.
  <?php
  while (list($key, $value) = each($arr)) {
      if (!($key % 2)) { // skip odd members
          continue;
      }
      do_something_odd($value);
  }

  $i = 0;
  while ($i++ < 5) {
      echo "Outer<br />\n";
      while (1) {
          echo "&nbsp;&nbsp;Middle<br />\n";
          while (1) {
              echo "&nbsp;&nbsp;Inner<br />\n";
              continue 3;
          }
          echo "This never gets output.<br />\n";
      }
      echo "Neither does this.<br />\n";




Lecturer Javedkhan M. Pathan [9998099262]                                   Page 37 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
    }
    ?>
    Omitting the semicolon after continue can lead to confusion. Here's an example of what
    you shouldn't do.
    <?php
       for ($i = 0; $i < 5; ++$i) {
           if ($i == 2)
               continue
           print "$i\n";
       }
    ?>
    One can expect the result to be :
    0
    1
    3
    4


    but this script will output :
    2
switch
   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.
   Note: Note that unlike some other languages, the continue statement applies to switch
   and acts similar to break. If you have a switch inside a loop and wish to continue to the
   next iteration of the outer loop, use continue 2.
   Note: Note that switch/case does loose comparision.
   The following two examples are two different ways to write the same thing, one using a
   series of if and elseif statements, and the other using the switch statement:
Example 16.1. switch structure
    <?php
    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;



Lecturer Javedkhan M. Pathan [9998099262]                                  Page 38 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
    case 2:
        echo "i equals 2";
        break;
    }
    ?>

Example 16.2. switch structure allows usage of strings
    <?php
    switch ($i) {
    case "apple":
        echo "i is apple";
        break;
    case "bar":
        echo "i is bar";
        break;
    case "cake":
        echo "i is cake";
        break;
    }
    ?>

    It is important to understand how the switch statement is executed in order to avoid
    mistakes. The switch statement executes line by line (actually, statement by statement).
    In the beginning, no code is executed. Only when a case statement is found with a value
    that matches the value of the switch expression does PHP begin to execute the
    statements. PHP continues to execute the statements until the end of the switch block, or
    the first time it sees a break statement. If you don't write a break statement at the end of
    a case's statement list, PHP will go on executing the statements of the following case.
    For example:
    <?php
    switch ($i)    {
    case 0:
        echo "i    equals 0";
    case 1:
        echo "i    equals 1";
    case 2:
        echo "i    equals 2";
    }
    ?>
    Here, if $i is equal to 0, PHP would execute all of the echo statements! If $i is equal to 1,
    PHP would execute the last two echo statements. You would get the expected behavior
    ('i equals 2' would be displayed) only if $i is equal to 2. Thus, it is important not to
    forget break statements (even though you may want to avoid supplying them on purpose
    under certain circumstances).
    In a switch statement, the condition is evaluated only once and the result is compared to
    each case statement. In an elseif statement, the condition is evaluated again. If your
    condition is more complicated than a simple compare and/or is in a tight loop, a switch
    may be faster.
    The statement list for a case can also be empty, which simply passes control into the
    statement list for the next case.

Lecturer Javedkhan M. Pathan [9998099262]                                     Page 39 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
   <?php
   switch ($i) {
   case 0:
   case 1:
   case 2:
       echo "i is less than 3 but not negative";
       break;
   case 3:
       echo "i is 3";
   }
   ?>
   A special case is the default case. This case matches anything that wasn't matched by the
   other cases. For example:
   <?php
   switch ($i)    {
   case 0:
       echo "i    equals 0";
       break;
   case 1:
       echo "i    equals 1";
       break;
   case 2:
       echo "i    equals 2";
       break;
   default:
       echo "i    is not equal to 0, 1 or 2";
   }
   ?>
   The case expression may be any expression that evaluates to a simple type, that is,
   integer or floating-point numbers and strings. Arrays or objects cannot be used here
   unless they are dereferenced to a simple type.
   The alternative syntax for control structures is supported with switches. For more
   information, see Alternative syntax for control structures.
   <?php
   switch ($i):
   case 0:
       echo "i equals      0";
       break;
   case 1:
       echo "i equals      1";
       break;
   case 2:
       echo "i equals      2";
       break;
   default:
       echo "i is not      equal to 0, 1 or 2";
   endswitch;
declare
   The declare construct is used to set execution directives for a block of code. The syntax
   of declare is similar to the syntax of other flow control constructs:
   declare (directive)


Lecturer Javedkhan M. Pathan [9998099262]                                  Page 40 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
         statement


    The directive section allows the behavior of the declare block to be set. Currently only
    one directive is recognized: the ticks directive. (See below for more information on the
    ticks directive)
    The statement part of the declare block will be executed -- how it is executed and what
    side effects occur during execution may depend on the directive set in the directive
    block.
    The declare construct can also be used in the global scope, affecting all code following
    it.
    <?php
    // these are the same:

    // you can use this:
    declare(ticks=1) {
        // entire script here
    }

    // or you can use this:
    declare(ticks=1);
    // entire script here
    ?>
Ticks
   A tick is an event that occurs for every N low-level statements executed by the parser
   within the declare block. The value for N is specified using ticks=N within the declare
   blocks's directive section.
   The event(s) that occur on each tick are specified using the register_tick_function(). See
   the example below for more details. Note that more than one event can occur for each
   tick.
Example 16.3. Profile a section of PHP code
    <?php
    // A function that records the time when it is called
    function profile($dump = FALSE)
    {
        static $profile;

         // Return the times stored in profile, then erase it
         if ($dump) {
             $temp = $profile;
             unset($profile);
             return $temp;
         }

         $profile[] = microtime();
    }

    // Set up a tick handler
    register_tick_function("profile");




Lecturer Javedkhan M. Pathan [9998099262]                                  Page 41 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
  // Initialize the function before the declare block
  profile();

  // Run a block of code, throw a tick every 2nd statement
  declare(ticks=2) {
      for ($x = 1; $x < 50; ++$x) {
          echo similar_text(md5($x), md5($x*$x)), "<br />;";
      }
  }

  // Display the data stored in the profiler
  print_r(profile(TRUE));
  ?>

  The example profiles the PHP code within the 'declare' block, recording the time at
  which every second low-level statement in the block was executed. This information can
  then be used to find the slow areas within particular segments of code. This process can
  be performed using other methods: using ticks is more convenient and easier to
  implement
return
  If called from within a function, the return() statement immediately ends execution of
  the current function, and returns its argument as the value of the function call. return()
  will also end the execution of an eval() statement or script file.
  If called from the global scope, then execution of the current script file is ended. If the
  current script file was include()ed or require()ed, then control is passed back to the
  calling file. Furthermore, if the current script file was include()ed, then the value given
  to return() will be returned as the value of the include() call. If return() is called from
  within the main script file, then script execution ends. If the current script file was
  named by the auto_prepend_file or auto_append_file configuration options in php.ini,
  then that script file's execution is ended.
  For more information, see Returning values.
  Note: Note that since return() is a language construct and not a function, the
  parentheses surrounding its arguments are not required. It is common to leave them out,
  and you actually should do so as PHP has less work to do in this case.
  Note: You should never use parentheses around your return variable when returning by
  reference, as this will not work. You can only return variables by reference, not the
  result of a statement. If you use return ($a); then you're not returning a variable, but the
  result of the expression ($a) (which is, of course, the value of $a).
require()
  The require() statement includes and evaluates the specific file.
  require() includes and evaluates a specific file. Detailed information on how this
  inclusion works is described in the documentation for include().
  require() and include() are identical in every way except how they handle failure. They
  both produce a Warning, but require() results in a Fatal Error. In other words, don't
  hesitate to use require() if you want a missing file to halt processing of the page.



Lecturer Javedkhan M. Pathan [9998099262]                                   Page 42 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
   include() does not behave this way, the script will continue regardless. Be sure to have
   an appropriate include_path setting as well.
Example 16.4. Basic require() examples
    <?php

    require 'prepend.php';

    require $somefile;

    require ('somefile.txt');

    ?>

    See the include() documentation for more examples.
    Note: Prior to PHP 4.0.2, the following applies: require() will always attempt to read
    the target file, even if the line it's on never executes. The conditional statement won't
    affect require(). However, if the line on which the require() occurs is not executed,
    neither will any of the code in the target file be executed. Similarly, looping structures
    do not affect the behaviour of require(). Although the code contained in the target file is
    still subject to the loop, the require() itself happens only once.
    Note: Because this is a language construct and not a function, it cannot be called using
    variable functions
include()
   The include() statement includes and evaluates the specified file.
   The documentation below also applies to require(). The two constructs are identical in
   every way except how they handle failure. They both produce a Warning, but require()
   results in a Fatal Error. In other words, use require() if you want a missing file to halt
   processing of the page. include() does not behave this way, the script will continue
   regardless. Be sure to have an appropriate include_path setting as well. Be warned that
   parse error in included file doesn't cause processing halting in PHP versions prior to PHP
   4.3.5. Since this version, it does.
   Files for including are first looked for in each include_path entry relative to the current
   working directory, and then in the directory of current script. E.g. if your include_path is
   libraries, current working directory is /www/, you included include/a.php and there is
   include "b.php" in that file, b.php is first looked in /www/libraries/ and then in
   /www/include/. If filename begins with ./ or ../, it is looked only in the current working
   directory.
   When a file is included, the code it contains inherits the variable scope of the line on
   which the include occurs. Any variables available at that line in the calling file will be
   available within the called file, from that point forward. However, all functions and
   classes defined in the included file have the global scope.
Example 16.5. Basic include() example
    vars.php
    <?php

    $color = 'green';
    $fruit = 'apple';


Lecturer Javedkhan M. Pathan [9998099262]                                   Page 43 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS

    ?>

    test.php
    <?php

    echo "A $color $fruit"; // A

    include 'vars.php';

    echo "A $color $fruit"; // A green apple

    ?>

   If the include occurs inside a function within the calling file, then all of the code
   contained in the called file will behave as though it had been defined inside that
   function. So, it will follow the variable scope of that function. An exception to this rule
   are magic constants which are evaluated by the parser before the include occurs.
Example 16.6. Including within functions
    <?php

    function foo()
    {
        global $color;

         include 'vars.php';

         echo "A $color $fruit";
    }

    /*   vars.php is in the scope of foo() so                *
     *   $fruit is NOT available outside of this             *
     *   scope. $color is because we declared it             *
     *   as global.                                          */

    foo();                           // A green apple
    echo "A $color $fruit";          // A green

    ?>

    When a file is included, parsing drops out of PHP mode and into HTML mode at the
    beginning of the target file, and resumes again at the end. For this reason, any code
    inside the target file which should be executed as PHP code must be enclosed within
    valid PHP start and end tags.
    If "URL fopen wrappers" are enabled in PHP (which they are in the default
    configuration), you can specify the file to be included using a URL (via HTTP or other
    supported wrapper - see Appendix O, List of Supported Protocols/Wrappers for a list of
    protocols) instead of a local pathname. If the target server interprets the target file as
    PHP code, variables may be passed to the included file using a URL request string as
    used with HTTP GET. This is not strictly speaking the same thing as including the file


Lecturer Javedkhan M. Pathan [9998099262]                                    Page 44 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
    and having it inherit the parent file's variable scope; the script is actually being run on
    the remote server and the result is then being included into the local script.
require_once()
   The require_once() statement includes and evaluates the specified file during the
   execution of the script. This is a behavior similar to the require() statement, with the only
   difference being that if the code from a file has already been included, it will not be
   included again. See the documentation for require() for more information on how this
   statement works.
   require_once() should be used in cases where the same file might be included and
   evaluated more than once during a particular execution of a script, and you want to be
   sure that it is included exactly once to avoid problems with function redefinitions,
   variable value reassignments, etc.
   For examples on using require_once() and include_once(), look at the » PEAR code
   included in the latest PHP source code distributions.
   Return values are the same as with include(). If the file was already included, this
   function returns TRUE
   Note: require_once() was added in PHP 4.0.1
   Note: Be aware, that the behaviour of require_once() and include_once() may not be
   what you expect on a non case sensitive operating system (such as Windows).
Example 16.11. require_once() is case insensitive on Windows
    <?php
    require_once "a.php"; // this will include a.php
    require_once "A.php"; // this will include a.php again on Windows! (PHP
     4 only)
    ?>
include_once()
   The include_once() statement includes and evaluates the specified file during the
   execution of the script. This is a behavior similar to the include() statement, with the
   only difference being that if the code from a file has already been included, it will not be
   included again. As the name suggests, it will be included just once.
   include_once() should be used in cases where the same file might be included and
   evaluated more than once during a particular execution of a script, and you want to be
   sure that it is included exactly once to avoid problems with function redefinitions,
   variable value reassignments, etc.
   For more examples on using require_once() and include_once(), look at the » PEAR
   code included in the latest PHP source code distributions.
   Return values are the same as with include(). If the file was already included, this
   function returns TRUE
   Note: include_once() was added in PHP 4.0.1
   Note: Be aware, that the behaviour of include_once() and require_once() may not be
   what you expect on a non case sensitive operating system (such as Windows).
Example 16.12. include_once() is case insensitive on Windows
    <?php
    include_once "a.php"; // this will include a.php
    include_once "A.php"; // this will include a.php again on Windows! (PHP



Lecturer Javedkhan M. Pathan [9998099262]                                      Page 45 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
     4 only)
    ?>


 Function:-
    User-defined functions
    Function arguments
    Returning values
    Variable functions
    Internal (built-in) functions

User-defined functions
   A function may be defined using syntax such as the following:
Example 17.1. Pseudo code to demonstrate function uses
    <?php
    function foo($arg_1, $arg_2, /* ..., */ $arg_n)
    {
        echo "Example function.\n";
        return $retval;
    }
    ?>

   Any valid PHP code may appear inside a function, even other functions and class
   definitions.
   Function names follow the same rules as other labels in PHP. A valid function name
   starts with a letter or underscore, followed by any number of letters, numbers, or
   underscores. As a regular expression, it would be expressed thus: [a-zA-Z_\x7f-\xff][a-
   zA-Z0-9_\x7f-\xff]*.
Example 17.2. Conditional functions
    <?php

    $makefoo = true;

    /* We can't call foo() from here
       since it doesn't exist yet,
       but we can call bar() */

    bar();

    if ($makefoo) {
      function foo()
      {
        echo "I don't exist until program execution reaches me.\n";
      }
    }

    /* Now we can safely call foo()
       since $makefoo evaluated to true */

    if ($makefoo) foo();


Lecturer Javedkhan M. Pathan [9998099262]                                 Page 46 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS

    function bar()
    {
      echo "I exist immediately upon program start.\n";
    }

    ?>
Example 17.3. Functions within functions
    <?php
    function foo()
    {
      function bar()
      {
        echo "I don't exist until foo() is called.\n";
      }
    }

    /* We can't call bar() yet
       since it doesn't exist. */

    foo();

    /* Now we can call bar(),
       foo()'s processesing has
       made it accessible. */

    bar();

    ?>

   All functions and classes in PHP have the global scope - they can be called outside a
   function even if they were defined inside and vice versa.
   PHP does not support function overloading, nor is it possible to undefine or redefine
   previously-declared functions.
   Note: Function names are case-insensitive, though it is usually good form to call
   functions as they appear in their declaration.
   PHP 3 does not support variable numbers of arguments to functions, although default
   arguments are supported (see Default argument values for more information). Both are
   supported, as of PHP 4: see Variable-length argument lists and the function references
   for func_num_args(), func_get_arg(), and func_get_args() for more information.
   It is possible to call recursive functions in PHP. However avoid recursive
   function/method calls with over 100-200 recursion levels as it can smash the stack and
   cause a termination of the current script.
Example 17.4. Recursive functions
    <?php
    function recursion($a)
    {
        if ($a < 20) {
            echo "$a\n";
            recursion($a + 1);
        }


Lecturer Javedkhan M. Pathan [9998099262]                                Page 47 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
    }
    ?>
Function arguments
   Information may be passed to functions via the argument list, which is a comma-
   delimited list of expressions.
   PHP supports passing arguments by value (the default), passing by reference, and default
   argument values. Variable-length argument lists are supported only in PHP 4 and later;
   see Variable-length argument lists and the function references for func_num_args(),
   func_get_arg(), and func_get_args() for more information. A similar effect can be
   achieved in PHP 3 by passing an array of arguments to a function:
Example 17.5. Passing arrays to functions
    <?php
    function takes_array($input)
    {
        echo "$input[0] + $input[1] = ", $input[0]+$input[1];
    }
    ?>


Making arguments be passed by reference
   By default, function arguments are passed by value (so that if you change the value of
   the argument within the function, it does not get changed outside of the function). If you
   wish to allow a function to modify its arguments, you must pass them by reference.
   If you want an argument to a function to always be passed by reference, you can prepend
   an ampersand (&) to the argument name in the function definition:
Example 17.6. Passing function parameters by reference
    <?php
    function add_some_extra(&$string)
    {
        $string .= 'and something extra.';
    }
    $str = 'This is a string, ';
    add_some_extra($str);
    echo $str;    // outputs 'This is a string, and something extra.'
    ?>


Default argument values
    A function may define C++-style default values for scalar arguments as follows:
    Example 17.7. Use of default parameters in functions
    <?php
    function makecoffee($type = "cappuccino")
    {
        return "Making a cup of $type.\n";
    }
    echo makecoffee();
    echo makecoffee(null);
    echo makecoffee("espresso");
    ?>



Lecturer Javedkhan M. Pathan [9998099262]                                  Page 48 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
    The output from the above snippet is:
    Making a cup of cappuccino.
    Making a cup of .
    Making a cup of espresso.

   Also PHP allows you to use arrays and special type NULL as default values, for
   example:
Example 17.8. Using non-scalar types as default values
    <?php
    function makecoffee($types = array("cappuccino"), $coffeeMaker = NULL)
    {
        $device = is_null($coffeeMaker) ? "hands" : $coffeeMaker;
        return "Making a cup of ".join(", ", $types)." with $device.\n";
    }
    echo makecoffee();
    echo makecoffee(array("cappuccino", "lavazza"), "teapot");
    ?>

   The default value must be a constant expression, not (for example) a variable, a class
   member or a function call.
   Note that when using default arguments, any defaults should be on the right side of any
   non-default arguments; otherwise, things will not work as expected. Consider the
   following code snippet:
Example 17.9. Incorrect usage of default function arguments
    <?php
    function makeyogurt($type = "acidophilus", $flavour)
    {
        return "Making a bowl of $type $flavour.\n";
    }

    echo makeyogurt("raspberry");           // won't work as expected
    ?>

    The output of the above example is:
    Warning: Missing argument 2 in call to makeyogurt() in
    /usr/local/etc/httpd/htdocs/php3test/functest.html on line 41
    Making a bowl of raspberry .

   Now, compare the above with this:
Example 17.10. Correct usage of default function arguments
    <?php
    function makeyogurt($flavour, $type = "acidophilus")
    {
        return "Making a bowl of $type $flavour.\n";
    }

    echo makeyogurt("raspberry");           // works as expected
    ?>

    The output of this example is:
    Making a bowl of acidophilus raspberry.


Lecturer Javedkhan M. Pathan [9998099262]                                 Page 49 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS

Returning values
    Values are returned by using the optional return statement. Any type may be returned,
    including lists and objects. This causes the function to end its execution immediately and
    pass control back to the line from which it was called. See return() for more information.
    Example 17.11. Use of return()
    <?php
    function square($num)
    {
        return $num * $num;
    }
    echo square(4);   // outputs '16'.
    ?>

   You can't return multiple values from a function, but similar results can be obtained by
   returning a list.
Example 17.12. Returning an array to get multiple values
    <?php
    function small_numbers()
    {
        return array (0, 1, 2);
    }
    list ($zero, $one, $two) = small_numbers();
    ?>

   To return a reference from a function, you have to use the reference operator & in both
   the function declaration and when assigning the returned value to a variable:
Example 17.13. Returning a reference from a function
    <?php
    function &returns_reference()
    {
        return $someref;
    }

    $newref =& returns_reference();
    ?>
Variable functions
   PHP supports the concept of variable functions. This means that if a variable name has
   parentheses appended to it, PHP will look for a function with the same name as whatever
   the variable evaluates to, and will attempt to execute it. Among other things, this can be
   used to implement callbacks, function tables, and so forth.
   Variable functions won't work with language constructs such as echo(), print(), unset(),
   isset(), empty(), include(), require() and the like. You need to use your own wrapper
   function to utilize any of these constructs as variable functions.
Example 17.14. Variable function example
    <?php
    function foo() {
        echo "In foo()<br />\n";
    }



Lecturer Javedkhan M. Pathan [9998099262]                                  Page 50 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
    function bar($arg = '')
    {
        echo "In bar(); argument was '$arg'.<br />\n";
    }

    // This is a wrapper function around echo
    function echoit($string)
    {
        echo $string;
    }

    $func = 'foo';
    $func();            // This calls foo()

    $func = 'bar';
    $func('test');      // This calls bar()

    $func = 'echoit';
    $func('test'); // This calls echoit()
    ?>

   You can also call an object's method by using the variable functions feature.
Example 17.15. Variable method example
    <?php
    class Foo
    {
        function Variable()
        {
            $name = 'Bar';
            $this->$name(); // This calls the Bar() method
        }

         function Bar()
         {
             echo "This is Bar";
         }
    }

    $foo = new Foo();
    $funcname = "Variable";
    $foo->$funcname(); // This calls $foo->Variable()

    ?>
Internal (built-in) functions
    PHP comes standard with many functions and constructs. There are also functions that
    require specific PHP extensions compiled in otherwise you'll get fatal "undefined
    function" errors. For example, to use image functions such as imagecreatetruecolor(),
    you'll need your PHP compiled with GD support. Or, to use mysql_connect() you'll need
    your PHP compiled in with MySQL support. There are many core functions that are
    included in every version of PHP like the string and variable functions. A call to
    phpinfo() or get_loaded_extensions() will show you which extensions are loaded into


Lecturer Javedkhan M. Pathan [9998099262]                                 Page 51 of 117
  SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
  BCA 302: BUILDING APPLICATION USING ASP/PHP
                  UNIT:-2 PHP 17 MARKS
     your PHP. Also note that many extensions are enabled by default and that the PHP
     manual is split up by extension. See the configuration, installation, and individual
     extension chapters, for information on how to setup your PHP.
     Reading and understanding a function's prototype is explained within the manual section
     titled how to read a function definition. It's important to realize what a function returns
     or if a function works directly on a passed in value. For example, str_replace() will
     return the modified string while usort() works on the actual passed in variable itself.
     Each manual page also has specific information for each function like information on
     function parameters, behavior changes, return values for both success and failure, and
     availability information. Knowing these important (yet often subtle) differences is
     crucial for writing correct PHP code.
 Variable length Argument Function:-
     func_num_args — Returns the number of arguments passed to the function
     func_get_arg — Return an item from the argument list
     func_get_args — Returns an array comprising a function's argument list

     call_user_func_array — Call a user function given with an array of parameters
     call_user_func — Call a user function given by the first parameter
     create_function — Create an anonymous (lambda-style) function
     function_exists — Return TRUE if the given function has been defined
     get_defined_functions — Returns an array of all defined functions
     register_shutdown_function — Register a function for execution on shutdown
     register_tick_function — Register a function for execution on each tick
     unregister_tick_function — De-register a function for execution on each tick

  func_num_args
     (PHP 4, PHP 5)
     func_num_args — Returns the number of arguments passed to the function
  Description
     int func_num_args ( void )
     Gets the number of arguments passed to the function.
     This function may be used in conjunction with func_get_arg() and func_get_args() to
     allow user-defined functions to accept variable-length argument lists.
  Return Values
     Returns the number of arguments passed into the current user-defined function.
  Errors/Exceptions
     Generates a warning if called from outside of a user-defined function.
  Examples
  Example 768. func_num_args() example
     <?php
     function foo()


  Lecturer Javedkhan M. Pathan [9998099262]                                   Page 52 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
   {
        $numargs = func_num_args();
        echo "Number of arguments: $numargs\n";
   }

   foo(1, 2, 3);        // Prints 'Number of arguments: 3'
   ?>
func_get_arg
   (PHP 4, PHP 5)
   func_get_arg — Return an item from the argument list
Description
   mixed func_get_arg ( int $arg_num )
   Gets the specified argument from a user-defined function's argument list.
   This function may be used in conjunction with func_get_args() and func_num_args() to
   allow user-defined functions to accept variable-length argument lists.
Parameters
   arg_num
   The argument offset. Function arguments are counted starting from zero.
Return Values
   Returns the specified argument, or FALSE on error.
Errors/Exceptions
   Generates a warning if called from outside of a user-defined function, or if arg_num is
   greater than the number of arguments actually passed.
Examples
Example 766. func_get_arg() example
   <?php
   function foo()
   {
         $numargs = func_num_args();
         echo "Number of arguments: $numargs<br />\n";
         if ($numargs >= 2) {
             echo "Second argument is: " . func_get_arg(1) . "<br />\n";
         }
   }

   foo (1, 2, 3);
   ?>
func_get_args
   (PHP 4, PHP 5)
   func_get_args — Returns an array comprising a function's argument list
Description
   array func_get_args ( void )
   Gets an array of the function's argument list.



Lecturer Javedkhan M. Pathan [9998099262]                                 Page 53 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
   This function may be used in conjunction with func_get_arg() and func_num_args() to
   allow user-defined functions to accept variable-length argument lists.
Return Values
   Returns an array in which each element is a copy of the corresponding member of the
   current user-defined function's argument list.
Errors/Exceptions
   Generates a warning if called from outside of a user-defined function.
Examples
Example 767. func_get_args() example
   <?php
   function foo()
   {
       $numargs = func_num_args();
       echo "Number of arguments: $numargs<br />\n";
       if ($numargs >= 2) {
           echo "Second argument is: " . func_get_arg(1) . "<br />\n";
       }
       $arg_list = func_get_args();
       for ($i = 0; $i < $numargs; $i++) {
           echo "Argument $i is: " . $arg_list[$i] . "<br />\n";
       }
   }

   foo(1, 2, 3);
   ?>
Variable Function:-

gettype
   (PHP 4, PHP 5)
   gettype — Get the type of a variable
Description
   string gettype ( mixed $var )
   Returns the type of the PHP variable var.
   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.
   Instead, use the is_* functions.
Return Values
   Possibles values for the returned string are:
   "boolean" (since PHP 4)
   "integer"
   "double" (for historical reasons "double" is returned in case of a float, and not simply
   "float")
   "string"

Lecturer Javedkhan M. Pathan [9998099262]                                   Page 54 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
    "array"
    "object"
   "resource" (since PHP 4)
   "NULL" (since PHP 4)
   "user function" (PHP 3 only, deprecated)
   "unknown type"
settype
   (PHP 4, PHP 5)
   settype — Set the type of a variable
Description
   bool settype ( mixed &$var, string $type )
   Set the type of variable var to 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)
Return Values
   Returns TRUE on success or FALSE on failure.
Examples
Example 2612. settype() example
   <?php
   $foo = "5bar"; // string
   $bar = true;   // boolean

   settype($foo, "integer"); // $foo is now 5  (integer)
   settype($bar, "string"); // $bar is now "1" (string)
   ?>
isset
   (PHP 4, PHP 5)
   isset — Determine whether a variable is set
Description
   bool isset ( mixed $var [, mixed $var [, $...]] )
   Determine whether a variable is set.



Lecturer Javedkhan M. Pathan [9998099262]                                  Page 55 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
    If a variable has been unset with unset(), it will no longer be set. isset() will return FALSE
    if testing a variable that has been set to NULL. Also note that a NULL byte ("\0") is not
    equivalent to the PHP NULL constant.
    If multiple parameters are supplied then isset() will return TRUE only if all of the
    parameters are set. Evaluation goes from left to right and stops as soon as an unset
    variable is encountered.
Parameters
    var
    The variable to be checked.
    var
    Another variable ..
    ...
Return Values
    Returns TRUE if var exists; FALSE otherwise.
Examples
Example 2608. isset() Examples
    <?php

    $var = '';

    // This will evaluate to TRUE so the text will be printed.
    if (isset($var)) {
        echo "This var is set so I will print.";
    }

    // In the next examples we'll use var_dump to output
    // the return value of isset().

    $a = "test";
    $b = "anothertest";

    var_dump(isset($a));      // TRUE
    var_dump(isset($a, $b)); // TRUE

    unset ($a);

    var_dump(isset($a));     // FALSE
    var_dump(isset($a, $b)); // FALSE

    $foo = NULL;
    var_dump(isset($foo));          // FALSE

    ?>

    This also work for elements in arrays:
    <?php

    $a = array ('test' => 1, 'hello' => NULL);



Lecturer Javedkhan M. Pathan [9998099262]                                      Page 56 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
  var_dump(isset($a['test']));                       // TRUE
  var_dump(isset($a['foo']));                        // FALSE
  var_dump(isset($a['hello']));                      // FALSE

  // The key 'hello' equals NULL so is considered unset
  // If you want to check for NULL key values then try:
  var_dump(array_key_exists('hello', $a)); // TRUE

  ?>
unset
  (PHP 4, PHP 5)
  unset — Unset a given variable
Description
  void unset ( mixed $var [, mixed $var [, mixed $...]] )
  unset() destroys the specified variables.
  The behavior of unset() inside of a function can vary depending on what type of variable
  you are attempting to destroy.
  If a globalized variable is unset() inside of a function, only the local variable is
  destroyed. The variable in the calling environment will retain the same value as before
  unset() was called.
  <?php
  function destroy_foo()
  {
      global $foo;
      unset($foo);
  }

  $foo = 'bar';
  destroy_foo();
  echo $foo;
  ?>
  The above example will output:
  bar


  If you would like to unset() a global variable inside of a function, you can use the
  $GLOBALS array to do so:
  <?php
  function foo()
  {
      unset($GLOBALS['bar']);
  }

  $bar = "something";
  foo();
  ?>
  If a variable that is PASSED BY REFERENCE is unset() inside of a function, only the
  local variable is destroyed. The variable in the calling environment will retain the same
  value as before unset() was called.

Lecturer Javedkhan M. Pathan [9998099262]                                 Page 57 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
  <?php
  function foo(&$bar)
  {
      unset($bar);
      $bar = "blah";
  }

  $bar = 'something';
  echo "$bar\n";

  foo($bar);
  echo "$bar\n";
  ?>
  The above example will output:
  something
  something


  If a static variable is unset() inside of a function, unset() destroys the variable only in
  the context of the rest of a function. Following calls will restore the previous value of a
  variable.
  <?php
  function foo()
  {
      static $bar;
      $bar++;
      echo "Before unset: $bar, ";
      unset($bar);
      $bar = 23;
      echo "after unset: $bar\n";
  }

  foo();
  foo();
  foo();
  ?>
  The above example will output:
  Before unset: 1, after unset: 23
  Before unset: 2, after unset: 23
  Before unset: 3, after unset: 23
Parameters
  var
  The variable to be unset.
  var
  Another variable .. ...
Return Values
  No value is returned.
ChangeLog

Lecturer Javedkhan M. Pathan [9998099262]                                   Page 58 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS

   Version                                      Description
   4.0.0         unset() became an expression. (In PHP 3, unset() would always return 1).
Examples
Example 2615. unset() example
   <?php
   // destroy a single variable
   unset($foo);

   // destroy a single element of an array
   unset($bar['quux']);

   // destroy more than one variable
   unset($foo1, $foo2, $foo3);
   ?>
   Note: Because this is a language construct and not a function, it cannot be called using
   variable functions
   Note: It is possible to unset even object properties visible in current context.
   Note: It is not possible to unset $this inside an object method since PHP 5.
strval
   (PHP 4, PHP 5)
   strval — Get string value of a variable
Description
   string strval ( mixed $var )
   Returns the string value of var. See the documentation on string for more information on
   converting to string.
   var may be any scalar type. You cannot use strval() on arrays or objects.
floatval
   (PHP 4 >= 4.2.0, PHP 5)
   floatval — Get float value of a variable
Description
   float floatval ( mixed $var )
   Gets the float value of var.
Parameters
   var
   May be any scalar type. You cannot use floatval() on arrays or objects.
Return Values
   The float value of the given variable.
Examples
Example 2595. floatval() Example
   <?php
   $var = '122.34343The';
   $float_value_of_var = floatval($var);



Lecturer Javedkhan M. Pathan [9998099262]                                  Page 59 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
    echo $float_value_of_var; // 122.34343
    ?>
intval
    (PHP 4, PHP 5)
    intval — Get the integer value of a variable
Description
    int intval ( mixed $var [, int $base] )
    Returns the integer value of var, using the specified base for the conversion (the default
    is base 10).
Parameters
    var
    The scalar value being converted to an integer
    base
    The base for the conversion (default is base 10)
Return Values
    The integer value of var on success, or 0 on failure. Empty arrays and objects return 0,
    non-empty arrays and objects return 1.
    The maximum value depends on the system. 32 bit systems have a maximum signed
    integer range of -2147483648 to 2147483647. So for example on such a system,
    intval('1000000000000') will return 2147483647. The maximum signed integer value for
    64 bit systems is 9223372036854775807.
    Strings will most likely return 0 although this depends on the leftmost characters of the
    string. The common rules of integer casting apply.
Examples
Example 2599. intval() examples
   The following examples are based on a 32 bit system.
    <?php
    echo intval(42);                                   //   42
    echo intval(4.2);                                  //   4
    echo intval('42');                                 //   42
    echo intval('+42');                                //   42
    echo intval('-42');                                //   -42
    echo intval(042);                                  //   34
    echo intval('042');                                //   42
    echo intval(1e10);                                 //   1410065408
    echo intval('1e10');                               //   1
    echo intval(0x1A);                                 //   26
    echo intval(42000000);                             //   42000000
    echo intval(420000000000000000000);                //   0
    echo intval('420000000000000000000');              //   2147483647
    echo intval(42, 8);                                //   42
    echo intval('42', 8);                              //   34
    ?>


Notes

Lecturer Javedkhan M. Pathan [9998099262]                                   Page 60 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
   Note: The base parameter has no effect unless the var parameter is a string.
print_r
   (PHP 4, PHP 5)
   print_r — Prints human-readable information about a variable
Description
   mixed print_r ( mixed $expression [, bool $return] )
   print_r() displays information about a variable in a way that's readable by humans.
   print_r(), var_dump() and var_export() will also show protected and private properties
   of objects with PHP 5.
   Remember that print_r() will move the array pointer to the end. Use reset() to bring it
   back to beginning.
Parameters
   expression
   The expression to be printed.
   return
   If you would like to capture the output of print_r(), use the return parameter. If this
   parameter is set to TRUE, print_r() will return its output, instead of printing it (which it
   does by default).
Return Values
   If given a string, integer or float, the value itself will be printed. If given an array, values
   will be presented in a format that shows keys and elements. Similar notation is used for
   objects.
Notes
   Note: This function internally uses the output buffering with this parameter so it can not
   be used inside ob_start() callback function.
ChangeLog
   Version                                          Description
                 The return parameter was added. If you need to capture the output of
   4.3.0         print_r() with an older version of PHP prior, use the output-control
                 functions.
                 Prior to PHP 4.0.4, print_r() will continue forever if given an array or
                 object that contains a direct or indirect reference to itself. An example is
   4.0.4
                 print_r($GLOBALS) because $GLOBALS is itself a global variable that
                 contains a reference to itself.
Examples
Example 2609. print_r() example
   <pre>
   <?php
   $a = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x', 'y', 'z
   '));
   print_r ($a);


Lecturer Javedkhan M. Pathan [9998099262]                                      Page 61 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
   ?>
   </pre>
   The above example will output:
   <pre>
   Array
   (
        [a] => apple
        [b] => banana
        [c] => Array
            (
                 [0] => x
                 [1] => y
                 [2] => z
            )
   )
   </pre>
Example 2610. return parameter example
   <?php
   $b = array ('m' => 'monkey', 'foo' => 'bar', 'x' => array ('x', 'y', 'z
   '));
   $results = print_r($b, true);//$results now contains outputfrom print_r
   ?>
 String Functions:-
   chr — Return a specific character
   ord — Return ASCII value of character
   strtolower — Make a string lowercase
   strtoupper — Make a string uppercase
   strlen — Get string length
   ltrim — Strip whitespace (or other characters) from the beginning of a string
   rtrim — Strip whitespace (or other characters) from the end of a string
   trim — Strip whitespace (or other characters) from the beginning and end of a string
   substr — Return part of a string
   strcmp — Binary safe string comparison
   strcasecmp — Binary safe case-insensitive string comparison
   strrpos — Find position of last occurrence of a char in a string
   strstr — Find first occurrence of a string
   stristr — Case-insensitive strstr()
   str_replace — Replace all occurrences of the search string with the replacement string
   strrev — Reverse a string
   echo — Output one or more strings
   print — Output a string

1. Chr:-
   (PHP 4, PHP 5)
   chr — Return a specific character


Lecturer Javedkhan M. Pathan [9998099262]                                 Page 62 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS

  Description
  string chr ( int $ascii )
  Returns a one-character string containing the character specified by ascii.
  This function complements ord().
  Parameters
  ascii
  The ascii code.
  Return Values
  Returns the specified character.
  Examples
  Example 2409. chr() example
  <?php
  $str = "The string ends in escape: ";
  $str .= chr(27); /* add an escape character at the end of $str */

  /* Often this is more useful */

  $str = sprintf("The string ends in escape: %c", 27);
  ?>
2. Ord:-
  (PHP 4, PHP 5)
  ord — Return ASCII value of character
  Description
  int ord ( string $string )
  Returns the ASCII value of the first character of string.
  This function complements chr().
  Parameters
  string
  A character.
  Return Values
  Returns the ASCII value as an integer.
  Examples
  Example 2436. ord() example
  <?php
  $str = "\n";
  if (ord($str) == 10) {
      echo "The first character of \$str is a line feed.\n";
  }
  ?>
3. strtolower
  (PHP 4, PHP 5)
  strtolower — Make a string lowercase


Lecturer Javedkhan M. Pathan [9998099262]                                Page 63 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS

  Description
  string strtolower ( string $str )
  Returns string with all alphabetic characters converted to lowercase.
  Note that 'alphabetic' is determined by the current locale. This means that in i.e. the
  default "C" locale, characters such as umlaut-A (Ä) will not be converted.
  Parameters
  str
  The input string.
  Return Values
  Returns the lowercased string.
  Examples
  Example 2482. strtolower() example
  <?php
  $str = "Mary Had A Little Lamb and She LOVED It So";
  $str = strtolower($str);
  echo
4. strtoupper
  (PHP 4, PHP 5)
  strtoupper — Make a string uppercase
  Description
  string strtoupper ( string $string )
  Returns string with all alphabetic characters converted to uppercase.
  Note that 'alphabetic' is determined by the current locale. For instance, in the default "C"
  locale characters such as umlaut-a (ä) will not be converted.
  Parameters
  string
  The input string.
  Return Values
  Returns the uppercased string.
  Examples
  Example 2483. strtoupper() example
  <?php
  $str = "Mary Had A Little Lamb and She LOVED It So";
  $str = strtoupper($str);
  echo $str; // Prints MARY HAD A LITTLE LAMB AND SHE LOVED IT SO
  ?>
5. strlen
  (PHP 4, PHP 5)
  strlen — Get string length
  Description
  int strlen ( string $string )


Lecturer Javedkhan M. Pathan [9998099262]                                   Page 64 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
  Returns the length of the given string.
  Parameters
  string
  The string being measured for length.
  Return Values
  The length of the string on success, and 0 if the string is empty.
  Examples
  Example 2471. A strlen() example
  <?php
  $str = 'abcdef';
  echo strlen($str); // 6

  $str = ' ab cd ';
  echo strlen($str); // 7
  ?>
6. ltrim
  (PHP 4, PHP 5)
  ltrim — Strip whitespace (or other characters) from the beginning of a string
  Description
  string ltrim ( string $str [, string $charlist] )
  Strip whitespace (or other characters) from the beginning of a string.
  Parameters
  str
  The input string.
  charlist
  You can also specify the characters you want to strip, by means of the charlist
  parameter. Simply list all characters that you want to be stripped. With .. you can specify
  a range of characters.
  Return Values
   This function returns a string with whitespace stripped from the beginning of str.
   Without the second parameter, ltrim() will strip these characters:
   " " (ASCII 32 (0x20)), an ordinary space.
   "\t" (ASCII 9 (0x09)), a tab.
   "\n" (ASCII 10 (0x0A)), a new line (line feed).
   "\r" (ASCII 13 (0x0D)), a carriage return.
   "\0" (ASCII 0 (0x00)), the NUL-byte.
   "\x0B" (ASCII 11 (0x0B)), a vertical tab.
  ChangeLog
  Version                   Description
  4.1.0         The charlist parameter was added.
  Examples

Lecturer Javedkhan M. Pathan [9998099262]                                  Page 65 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
  Example 2431. Usage example of ltrim()
  <?php

  $text = "\t\tThese are a few words :) ...               ";
  $binary = "\x09Example string\x0A";
  $hello = "Hello World";
  var_dump($text, $binary, $hello);

  print "\n";


  $trimmed = ltrim($text);
  var_dump($trimmed);

  $trimmed = ltrim($text, " \t.");
  var_dump($trimmed);

  $trimmed = ltrim($hello, "Hdle");
  var_dump($trimmed);

  // trim the ASCII control characters at the beginning of $binary
  // (from 0 to 31 inclusive)
  $clean = ltrim($binary, "\x00..\x1F");
  var_dump($clean);

  ?>
  The above example will output:
  string(32) "        These are a few words :) ...               "
  string(16) "    Example string
  "
  string(11) "Hello World"

  string(30) "These are a few words :) ...            "
  string(30) "These are a few words :) ...            "
  string(7) "o World"
  string(15) "Example string
  "
7. rtrim
  (PHP 4, PHP 5)
  rtrim — Strip whitespace (or other characters) from the end of a string
  Description
  string rtrim ( string $str [, string $charlist] )
  This function returns a string with whitespace stripped from the end of str.
  Without the second parameter, rtrim() will strip these characters:
       " " (ASCII 32 (0x20)), an ordinary space.
       "\t" (ASCII 9 (0x09)), a tab.
       "\n" (ASCII 10 (0x0A)), a new line (line feed).
       "\r" (ASCII 13 (0x0D)), a carriage return.
       "\0" (ASCII 0 (0x00)), the NUL-byte.


Lecturer Javedkhan M. Pathan [9998099262]                                   Page 66 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
          "\x0B" (ASCII 11 (0x0B)), a vertical tab.
  Parameters
  str
  The input string.
  charlist
  You can also specify the characters you want to strip, by means of the charlist
  parameter. Simply list all characters that you want to be stripped. With .. you can specify
  a range of characters.
  Return Values
  Returns the modified string.
  ChangeLog
  Version                     Description
  4.1.0           The charlist parameter was added.
  Examples
  Example 2439. Usage example of rtrim()
  <?php

  $text = "\t\tThese are a few words :) ...             ";
  $binary = "\x09Example string\x0A";
  $hello = "Hello World";
  var_dump($text, $binary, $hello);

  print "\n";

  $trimmed = rtrim($text);
  var_dump($trimmed);

  $trimmed = rtrim($text, " \t.");
  var_dump($trimmed);

  $trimmed = rtrim($hello, "Hdle");
  var_dump($trimmed);

  // trim the ASCII control characters at the end of $binary
  // (from 0 to 31 inclusive)
  $clean = rtrim($binary, "\x00..\x1F");
  var_dump($clean);

  ?>
  The above example will output:
  string(32) "        These are a few words :) ...               "
  string(16) "    Example string
  "
  string(11) "Hello World"

  string(30) "               These are a few words :) ..."
  string(26) "               These are a few words :)"


Lecturer Javedkhan M. Pathan [9998099262]                                 Page 67 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
  string(9) "Hello Wor"
  string(15) "    Example string"
8. trim
  (PHP 4, PHP 5)
  trim — Strip whitespace (or other characters) from the beginning and end of a string
  Description
  string trim ( string $str [, string $charlist] )
  This function returns a string with whitespace stripped from the beginning and end of
  str. Without the second parameter, trim() will strip these characters:
      o " " (ASCII 32 (0x20)), an ordinary space.
      o "\t" (ASCII 9 (0x09)), a tab.
      o "\n" (ASCII 10 (0x0A)), a new line (line feed).
      o "\r" (ASCII 13 (0x0D)), a carriage return.
      o "\0" (ASCII 0 (0x00)), the NUL-byte.
      o "\x0B" (ASCII 11 (0x0B)), a vertical tab.
  Parameters
  str
  The string that will be trimmed.
  charlist
  Optionally, the stripped characters can also be specified using the charlist parameter.
  Simply list all characters that you want to be stripped. With .. you can specify a range of
  characters.
  Return Values
  The trimmed string.
  ChangeLog
  Version                        Description
  4.1.0         The optional charlist parameter was added.
  Examples
  Example 2492. Usage example of trim()
  <?php

  $text   = "\t\tThese are a few words :) ...              ";
  $binary = "\x09Example string\x0A";
  $hello = "Hello World";
  var_dump($text, $binary, $hello);

  print "\n";

  $trimmed = trim($text);
  var_dump($trimmed);

  $trimmed = trim($text, " \t.");
  var_dump($trimmed);




Lecturer Javedkhan M. Pathan [9998099262]                                  Page 68 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
  $trimmed = trim($hello, "Hdle");
  var_dump($trimmed);

  // trim the ASCII control characters at the beginning and end of $binar
  y
  // (from 0 to 31 inclusive)
  $clean = trim($binary, "\x00..\x1F");
  var_dump($clean);

  ?>
  The above example will output:
  string(32) "        These are a few words :) ...    "
  string(16) "    Example string
  "
  string(11) "Hello World"

  string(28) "These are a few words :) ..."
  string(24) "These are a few words :)"
  string(5) "o Wor"
  string(14) "Example string"




  Example 2493. Trimming array values with trim()
  <?php
  function trim_value(&$value)
  {
      $value = trim($value);
  }

  $fruit = array('apple','banana ', ' cranberry ');
  var_dump($fruit);

  array_walk($fruit, 'trim_value');
  var_dump($fruit);

  ?>
  The above example will output:
  array(3) {
    [0]=>
    string(5) "apple"
    [1]=>
    string(7) "banana "
    [2]=>
    string(11) " cranberry "
  }
  array(3) {
    [0]=>
    string(5) "apple"
    [1]=>
    string(6) "banana"
    [2]=>


Lecturer Javedkhan M. Pathan [9998099262]                 Page 69 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
      string(9) "cranberry"
  }
9. substr
  (PHP 4, PHP 5)
  substr — Return part of a string
  Description
  string substr ( string $string, int $start [, int $length] )
  Returns the portion of string specified by the start and length parameters.
  Parameters
  string
  The input string.
  start
  If start is non-negative, the returned string will start at the start'th position in string,
  counting from zero. For instance, in the string 'abcdef', the character at position 0 is 'a',
  the character at position 2 is 'c', and so forth.
  If start is negative, the returned string will start at the start'th character from the end
  of string.
  Example 2489. Using a negative start
  <?php
  $rest = substr("abcdef", -1);    // returns "f"
  $rest = substr("abcdef", -2);    // returns "ef"
  $rest = substr("abcdef", -3, 1); // returns "d"
  ?>

  length
  If length is given and is positive, the string returned will contain at most length
  characters beginning from start (depending on the length of string). If string is less
  than or equal to start characters long, FALSE will be returned.
  If length is given and is negative, then that many characters will be omitted from the
  end of string (after the start position has been calculated when a start is negative). If
  start denotes a position beyond this truncation, an empty string will be returned.
  Example 2490. Using a negative length
  <?php
  $rest    =   substr("abcdef",   0, -1);     //   returns   "abcde"
  $rest    =   substr("abcdef",   2, -1);     //   returns   "cde"
  $rest    =   substr("abcdef",   4, -4);     //   returns   ""
  $rest    =   substr("abcdef",   -3, -1);    //   returns   "de"
  ?>


  Return Values
  Returns the extracted part of string.
  Examples
  Example 2491. Basic substr() usage
  <?php
  echo substr('abcdef', 1);               // bcdef


Lecturer Javedkhan M. Pathan [9998099262]                                   Page 70 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
  echo   substr('abcdef',     1, 3);    //   bcd
  echo   substr('abcdef',     0, 4);    //   abcd
  echo   substr('abcdef',     0, 8);    //   abcdef
  echo   substr('abcdef',     -1, 1);   //   f

  // Accessing single characters in a            string
  // can also be achived using "curly            braces"
  $string = 'abcdef';
  echo $string{0};                 //            a
  echo $string{3};                 //            d
  echo $string{strlen($string)-1}; //            f

  ?>
10. strcmp
  (PHP 4, PHP 5)
  strcmp — Binary safe string comparison
  Description
  int strcmp ( string $str1, string $str2 )
  Note that this comparison is case sensitive.
  Parameters
  str1
  The first string.
  str2
  The second string.
  Return Values
  Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are
  equal.
11. strcasecmp
  (PHP 4, PHP 5)
  strcasecmp — Binary safe case-insensitive string comparison
  Description
  int strcasecmp ( string $str1, string $str2 )
  Binary safe case-insensitive string comparison.
  Parameters
  str1
  The first string
  str2
  The second string
  Return Values
  Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are
  equal.
  Examples
  Example 2463. strcasecmp() example


Lecturer Javedkhan M. Pathan [9998099262]                                  Page 71 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
  <?php
  $var1 = "Hello";
  $var2 = "hello";
  if (strcasecmp($var1, $var2) == 0) {
      echo '$var1 is equal to $var2 in a case-
  insensitive string comparison';
  }
  ?>
12. strrpos
  (PHP 4, PHP 5)
  strrpos — Find position of last occurrence of a char in a string
  Description
  int strrpos ( string $haystack, string $needle [, int $offset] )
  Returns the numeric position of the last occurrence of needle in the haystack string.
  Note that the needle in this case can only be a single character in PHP 4. If a string is
  passed as the needle, then only the first character of that string will be used.
  If needle is not found, returns FALSE.
  It is easy to mistake the return values for "character found at position 0" and "character
  not found". Here's how to detect the difference:
  <?php

  // in PHP 4.0.0 and newer:
  $pos = strrpos($mystring, "b");
  if ($pos === false) { // note: three equal signs
      // not found...
  }

  // in versions older than 4.0.0:
  $pos = strrpos($mystring, "b");
  if (is_bool($pos) && !$pos) {
       // not found...
  }
  ?>
  If needle is not a string, it is converted to   an integer and applied as the ordinal value of
  a character.
  Note: As of PHP 5.0.0 offset may be specified to begin searching an arbitrary number
  of characters into the string. Negative values will stop searching at an arbitrary point
  prior to the end of the string.
  Note: The needle may be a string of more than one character as of PHP 5.0.0.
  Parameters
  haystack
  needle
  offset
13. strstr
  (PHP 4, PHP 5)
  strstr — Find first occurrence of a string
  Description
Lecturer Javedkhan M. Pathan [9998099262]                                      Page 72 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
  string strstr ( string $haystack, string $needle, bool $before_needle )
  Returns part of haystack string from the first occurrence of needle to the end of
  haystack.
  Note: This function is case-sensitive. For case-insensitive searches, use stristr().
  Note: If you only want to determine if a particular needle occurs within haystack, use
  the faster and less memory intensive function strpos() instead.
  Parameters
  haystack
  The input string.
  needle
  If needle is not a string, it is converted to an integer and applied as the ordinal value of
  a character.
  before_needle
  If TRUE (the default is FALSE), strstr() returns   the part of the haystack before the first
  occurence of the needle.
  Return Values
  Returns the portion of string, or FALSE if needle is not found.
  ChangeLog
  Version                     Description
  6.0.0         Added the before_needle parameter.
  4.3.0         strstr() was made binary safe.
  Examples
  Example 2478. strstr() example
  <?php
  $email = 'name@example.com';
  $domain = strstr($email, '@');
  echo $domain; // prints @example.com

  $user = strstr($email, '@', true);
  echo $user; // prints name
  ?>


14. stristr
  (PHP 4, PHP 5)
  stristr — Case-insensitive strstr()
  Description
  string stristr ( string $haystack, string $needle, bool $before_needle )
  Returns all of haystack from the first occurrence of needle to the end.
  Parameters
  haystack
  The string to search in
  needle


Lecturer Javedkhan M. Pathan [9998099262]                                     Page 73 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
  If needle is not a string, it is converted to an integer and applied as the ordinal value of
  a character.
  before_needle
  If TRUE (the default is FALSE), stristr() returns the part of the haystack   before the first
  occurence of the needle.
  needle and haystack are examined in a case-insensitive manner.
  Return Values
  Returns the matched substring. If needle is not found, returns FALSE.
  ChangeLog
  Version                     Description
  6.0.0         Added the before_needle parameter.
  4.3.0         stristr() was made binary safe.
  Examples
  Example 2468. stristr() example
  <?php
     $email = 'USER@EXAMPLE.com';
     echo stristr($email, 'e'); // outputs ER@EXAMPLE.com
     echo stristr($email, 'e', true); // outputs US
  ?>

  Example 2469. Testing if a string is found or not
  <?php
     $string = 'Hello World!';
     if(stristr($string, 'earth') === FALSE) {
       echo '"earth" not found in string';
     }
  // outputs: "earth" not found in string
  ?>

  Example 2470. Using a non "string" needle
  <?php
     $string = 'APPLE';
     echo stristr($string, 97); // 97 = lowercase a
  // outputs: APPLE
  ?>


  Notes
  Note: This function is binary-safe.
15. str_replace
  (PHP 4, PHP 5)
  str_replace — Replace all occurrences of the search string with the replacement string
  Description
  mixed str_replace ( mixed $search, mixed $replace, mixed $subject [, int &$count] )


Lecturer Javedkhan M. Pathan [9998099262]                                   Page 74 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
  This function returns a string or an array with all occurrences of search in subject
  replaced with the given replace value.
  If you don't need fancy replacing rules (like regular expressions), you should always use
  this function instead of ereg_replace() or preg_replace().
  Parameters
  If search and replace are arrays, then str_replace() takes a value from each array and
  uses them to do search and replace on subject. If replace has fewer values than
  search, then an empty string is used for the rest of replacement values. If search is an
  array and replace is a string, then this replacement string is used for every value of
  search. The converse would not make sense, though.
  If search or replace are arrays, their elements are processed first to last.
  search
  replace
  subject
  If subject is an array, then the search and replace   is performed with every entry of
  subject, and the return value is an array as well.
  count
  Note: If passed, this will hold the number of matched and replaced needles.
  Return Values
  This function returns a string or an array with the replaced values.
  ChangeLog
  Version                                       Description
  5.0.0         The count parameter was added.
                The behaviour of this function changed. In older versions a bug existed
                when using arrays as both search and replace parameters which caused
                empty search indexes to be skipped without advancing the internal pointer
  4.3.3
                on the replace array. This has been corrected in PHP 4.3.3, any scripts
                which relied on this bug should remove empty search values prior to
                calling this function in order to mimic the original behavior.
  4.0.5         Most parameters can now be an array.
  Examples
  Example 2458. str_replace() examples
  <?php
  // Provides: <body text='black'>
  $bodytag = str_replace("%body%", "black", "<body text='%body%'>");

  // Provides: Hll Wrld f PHP
  $vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U");
  $onlyconsonants = str_replace($vowels, "", "Hello World of PHP");

  // Provides: You should eat pizza, beer, and ice cream every day
  $phrase = "You should eat fruits, vegetables, and fiber every day.";
  $healthy = array("fruits", "vegetables", "fiber");
  $yummy   = array("pizza", "beer", "ice cream");


Lecturer Javedkhan M. Pathan [9998099262]                                  Page 75 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS

  $newphrase = str_replace($healthy, $yummy, $phrase);

  // Use of the count parameter is available as of PHP 5.0.0
  $str = str_replace("ll", "", "good golly miss molly!", $count);
  echo $count; // 2

  // Order of replacement
  $str     = "Line 1\nLine 2\rLine 3\r\nLine 4\n";
  $order   = array("\r\n", "\n", "\r");
  $replace = '<br />';
  // Processes \r\n's first so they aren't converted twice.
  $newstr = str_replace($order, $replace, $str);

  // Outputs: apearpearle pear
  $letters = array('a', 'p');
  $fruit   = array('apple', 'pear');
  $text    = 'a p';
  $output = str_replace($letters, $fruit, $text);
  echo $output;
  ?>
16. strrev
  (PHP 4, PHP 5)
  strrev — Reverse a string
  Description
  string strrev ( string $string )
  Returns string, reversed.
  Parameters
  string
  The string to be reversed.
  Return Values
  Returns the reversed string.
  Examples
  Example 2475. Reversing a string with strrev()
  <?php
  echo strrev("Hello world!"); // outputs "!dlrow olleH"
  ?>


17. echo
  (PHP 4, PHP 5)
  echo — Output one or more strings
  Description
  void echo ( string $arg1 [, string $...] )
  Outputs all parameters.
  echo() is not actually a function (it is a language construct), so you are not required to
  use parentheses with it. echo() (unlike some other language constructs) does not behave

Lecturer Javedkhan M. Pathan [9998099262]                                 Page 76 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
  like a function, so it cannot always be used in the context of a function. Additionally, if
  you want to pass more than one parameter to echo(), the parameters must not be
  enclosed within parentheses.
  echo() also has a shortcut syntax, where you can immediately follow the opening tag
  with an equals sign. This short syntax only works with the short_open_tag configuration
  setting enabled.
  I have <?=$foo?> foo.
  Parameters
  arg1
  The parameter to output.
  ...
  Return Values
  No value is returned.
  Examples
  Example 2418. echo() examples
  <?php
  echo "Hello World";

  echo "This spans
  multiple lines. The newlines will be
  output as well";

  echo "This spans\nmultiple lines. The newlines will be\noutput as well.
  ";

  echo "Escaping characters is done \"Like this\".";

  // You can use variables inside of an echo statement
  $foo = "foobar";
  $bar = "barbaz";

  echo "foo is $foo"; // foo is foobar

  // You can also use arrays
  $baz = array("value" => "foo");

  echo "this is {$baz['value']} !"; // this is foo !

  // Using single quotes will print the variable name, not the value
  echo 'foo is $foo'; // foo is $foo

  // If you are not using any other characters, you can just echo variabl
  es
  echo $foo;          // foobar
  echo $foo,$bar;     // foobarbarbaz

  // Some people prefer passing multiple parameters to echo over concaten
  ation.
  echo 'This ', 'string ', 'was ', 'made ', 'with multiple parameters.',
  chr(10);


Lecturer Javedkhan M. Pathan [9998099262]                                  Page 77 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
  echo 'This ' . 'string ' . 'was ' . 'made ' . 'with concatenation.' . "
  \n";

  echo <<<END
  This uses the "here document" syntax to output
  multiple lines with $variable interpolation. Note
  that the here document terminator must appear on a
  line with just a semicolon. no extra whitespace!
  END;

  // Because echo does not behave like a function, the following code is
  invalid.
  ($some_var) ? echo 'true' : echo 'false';

  // However, the following examples will work:
  ($some_var) ? print 'true' : print 'false'; // print is also a construc
  t, but
                                              // it behaves like a functi
  on, so
                                              // it may be used in this c
  ontext.
  echo $some_var ? 'true': 'false'; // changing the statement around
  ?>
18. print
  (PHP 4, PHP 5)
  print — Output a string
  Description
  int print ( string $arg )
  Outputs arg.
  print() is not actually a real function (it is a language construct) so you are not required
  to use parentheses with its argument list.
  For a short discussion about the differences between print() and echo(), see this FAQTs
  Knowledge Base Article: »
  http://www.faqts.com/knowledge_base/view.phtml/aid/1/fid/40
  Parameters
  arg
  The input data.
  Return Values
  Returns 1, always.
  Examples
  Example 2438. print() examples
  <?php
  print("Hello World");

  print "print() also works without parentheses.";

  print "This spans
  multiple lines. The newlines will be


Lecturer Javedkhan M. Pathan [9998099262]                                   Page 78 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
  output as well";

  print "This spans\nmultiple lines. The newlines will be\noutput as well
  .";

  print "escaping characters is done \"Like this\".";

  // You can use variables inside of a print statement
  $foo = "foobar";
  $bar = "barbaz";

  print "foo is $foo"; // foo is foobar

  // You can also use arrays
  $bar = array("value" => "foo");

  print "this is {$bar['value']} !"; // this is foo !

  // Using single quotes will print the variable name, not the value
  print 'foo is $foo'; // foo is $foo

  // If you are not using any other characters, you can just print variab
  les
  print $foo;          // foobar

  print <<<END
  This uses the "here document" syntax to output
  multiple lines with $variable interpolation. Note
  that the here document terminator must appear on a
  line with just a semicolon no extra whitespace!
  END;
  ?>

  Extra:-
  addcslashes — Quote string with slashes in a C style
  addslashes — Quote string with slashes
  bin2hex — Convert binary data into hexadecimal representation
  chop — Alias of rtrim()
  chunk_split — Split a string into smaller chunks
  convert_cyr_string — Convert from one Cyrillic character set to another
  convert_uudecode — Decode a uuencoded string
  convert_uuencode — Uuencode a string
  count_chars — Return information about characters used in a string
  crc32 — Calculates the crc32 polynomial of a string
  crypt — One-way string encryption (hashing)
  explode — Split a string by string
  fprintf — Write a formatted string to a stream
  get_html_translation_table — Returns the translation table used by htmlspecialchars()
  and htmlentities()
  hebrev — Convert logical Hebrew text to visual text


Lecturer Javedkhan M. Pathan [9998099262]                               Page 79 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
  hebrevc — Convert logical Hebrew text to visual text with newline conversion
  html_entity_decode — Convert all HTML entities to their applicable characters
  htmlentities — Convert all applicable characters to HTML entities
  htmlspecialchars_decode — Convert special HTML entities back to characters
  htmlspecialchars — Convert special characters to HTML entities
  implode — Join array elements with a string
  join — Alias of implode()
  levenshtein — Calculate Levenshtein distance between two strings
  localeconv — Get numeric formatting information
  md5_file — Calculates the md5 hash of a given file
  md5 — Calculate the md5 hash of a string
  metaphone — Calculate the metaphone key of a string
  money_format — Formats a number as a currency string
  nl_langinfo — Query language and locale information
  nl2br — Inserts HTML line breaks before all newlines in a string
  number_format — Format a number with grouped thousands
  parse_str — Parses the string into variables
  printf — Output a formatted string
  quoted_printable_decode — Convert a quoted-printable string to an 8 bit string
  quotemeta — Quote meta characters
  setlocale — Set locale information
  sha1_file — Calculate the sha1 hash of a file
  sha1 — Calculate the sha1 hash of a string
  similar_text — Calculate the similarity between two strings
  soundex — Calculate the soundex key of a string
  sprintf — Return a formatted string
  sscanf — Parses input from a string according to a format
  str_getcsv — Parse a CSV string into an array
  str_ireplace — Case-insensitive version of str_replace().
  str_pad — Pad a string to a certain length with another string
  str_repeat — Repeat a string
  str_rot13 — Perform the rot13 transform on a string
  str_shuffle — Randomly shuffles a string
  str_split — Convert a string to an array
  str_word_count — Return information about words used in a string
  strchr — Alias of strstr()
  strcoll — Locale based string comparison
  strcspn — Find length of initial segment not matching mask
  strip_tags — Strip HTML and PHP tags from a string
  stripcslashes — Un-quote string quoted with addcslashes()
  stripos — Find position of first occurrence of a case-insensitive string
  stripslashes — Un-quote string quoted with addslashes()
  strnatcasecmp — Case insensitive string comparisons using a "natural order" algorithm
  strnatcmp — String comparisons using a "natural order" algorithm
  strncasecmp — Binary safe case-insensitive string comparison of the first n characters

Lecturer Javedkhan M. Pathan [9998099262]                               Page 80 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
  strncmp — Binary safe string comparison of the first n characters
  strpbrk — Search a string for any of a set of characters
  strpos — Find position of first occurrence of a string
  strrchr — Find the last occurrence of a character in a string
  strripos — Find position of last occurrence of a case-insensitive string in a string
  strspn — Find length of initial segment matching mask
  strtok — Tokenize string
  strtr — Translate certain characters
  substr_compare — Binary safe comparison of 2 strings from an offset, up to length
  characters
  substr_count — Count the number of substring occurrences
  substr_replace — Replace text within a portion of a string

  ucfirst — Make a string's first character uppercase
  ucwords — Uppercase the first character of each word in a string
  vfprintf — Write a formatted string to a stream
  vprintf — Output a formatted string
  vsprintf — Return a formatted string
  wordwrap — Wraps a string to a given number of characters
 Mathematical Functions:-
  abs — Absolute value
  ceil — Round fractions up
  floor — Round fractions down
  round — Rounds a float
  fmod — Returns the floating point remainder (modulo) of the division of the arguments
  max — Find highest value
  min — Find lowest value
  pow — Exponential expression
  sqrt — Square root
  rand — Generate a random integer

  Extra:-
  acos — Arc cosine
  acosh — Inverse hyperbolic cosine
  asin — Arc sine
  asinh — Inverse hyperbolic sine
  atan2 — Arc tangent of two variables
  atan — Arc tangent
  atanh — Inverse hyperbolic tangent
  base_convert — Convert a number between arbitrary bases
  bindec — Binary to decimal
  cos — Cosine
  cosh — Hyperbolic cosine


Lecturer Javedkhan M. Pathan [9998099262]                                Page 81 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
  decbin — Decimal to binary
  dechex — Decimal to hexadecimal
  decoct — Decimal to octal
  deg2rad — Converts the number in degrees to the radian equivalent
  exp — Calculates the exponent of e
  expm1 — Returns exp(number) - 1, computed in a way that is accurate even when the
  value of number is close to zero
  getrandmax — Show largest possible random value
  hexdec — Hexadecimal to decimal
  hypot — Calculate the length of the hypotenuse of a right-angle triangle
  is_finite — Finds whether a value is a legal finite number
  is_infinite — Finds whether a value is infinite
  is_nan — Finds whether a value is not a number
  lcg_value — Combined linear congruential generator
  log10 — Base-10 logarithm
  log1p — Returns log(1 + number), computed in a way that is accurate even when the
  value of number is close to zero
  log — Natural logarithm
  mt_getrandmax — Show largest possible random value
  mt_rand — Generate a better random value
  mt_srand — Seed the better random number generator
  octdec — Octal to decimal
  pi — Get value of pi
  rad2deg — Converts the radian number to the equivalent number in degrees
  sin — Sine
  sinh — Hyperbolic sine
  srand — Seed the random number generator
  tan — Tangent
  tanh — Hyperbolic tangent


1. abs
  (PHP 4, PHP 5)
  abs — Absolute value
  Description
  number abs ( mixed $number )
  Returns the absolute value of number.
  Parameters
  number
  The numeric value to process
  Return Values
  The absoulte value of number. If the argument number is of type float, the return type is
  also float, otherwise it is integer (as float usually has a bigger value range than integer).

Lecturer Javedkhan M. Pathan [9998099262]                                    Page 82 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS

   Examples
   Example 1146. abs() example
   <?php
   $abs = abs(-4.2); // $abs = 4.2; (double/float)
   $abs2 = abs(5);   // $abs2 = 5; (integer)
   $abs3 = abs(-5); // $abs3 = 5; (integer)
   ?>
2. ceil
   (PHP 4, PHP 5)
   ceil — Round fractions up
   Description
   float ceil ( float $value )
   Returns the next highest integer value by rounding up value if necessary.
   Parameters
   value
   The value to round
   Return Values
   value   rounded up to the next highest integer. The return value of ceil() is still of type
   float as the value range of float is usually bigger than that of integer.
   Examples
   Example 1149. ceil() example
   <?php
   echo ceil(4.3);          // 5
   echo ceil(9.999);        // 10
   echo ceil(-3.14);        // -3
   ?>
3. floor
   (PHP 4, PHP 5)
   floor — Round fractions down
   Description
   float floor ( float $value )
   Returns the next lowest integer value by rounding down value if necessary.
   Parameters
   number
   The numeric value to round
   Return Values
   arg rounded to the next lowest integer. The return value of floor() is still of type float
   because the value range of float is usually bigger than that of integer.
   Examples
   Example 1156. floor() example
   <?php
   echo floor(4.3);         // 4


Lecturer Javedkhan M. Pathan [9998099262]                                     Page 83 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
  echo floor(9.999); // 9
  echo floor(-3.14); // -4
  ?>
4. round
  (PHP 4, PHP 5)
  round — Rounds a float
  Description
  float round ( float $val [, int $precision] )
  Returns the rounded value of val to specified precision (number of digits after the
  decimal point). precision can also be negative or zero (default).
  Note: PHP doesn't handle strings like "12,300.2" correctly by default. See converting
  from strings.
  Note: The precision parameter was introduced in PHP 4.
  Parameters
  val
  The value to round
  precision
  The optional number of decimal digits to round to, defaults to 0
  Return Values
  The rounded value
  Examples
  Example 1168. round() examples
  <?php
  echo round(3.4);                //   3
  echo round(3.5);                //   4
  echo round(3.6);                //   4
  echo round(3.6, 0);             //   4
  echo round(1.95583, 2);         //   1.96
  echo round(1241757, -3);        //   1242000
  echo round(5.045, 2);           //   5.05
  echo round(5.055, 2);           //   5.06
  ?>
5. fmod
  (PHP 4 >= 4.2.0, PHP 5)
  fmod — Returns the floating point remainder (modulo) of the division of the arguments
  Description
  float fmod ( float $x, float $y )
  Returns the floating point remainder of dividing the dividend (x) by the divisor (y). The
  reminder (r) is defined as: x = i * y + r, for some integer i. If y is non-zero, r has the
  same sign as x and a magnitude less than the magnitude of y.
  Parameters
  x
  The dividend
  y


Lecturer Javedkhan M. Pathan [9998099262]                                 Page 84 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
  The divisor
  Return Values
  The floating point remainder of x/y
  Examples
  Example 1157. Using fmod()
  <?php
  $x = 5.7;
  $y = 1.3;
  $r = fmod($x, $y);
  // $r equals 0.5, because 4 * 1.3 + 0.5 = 5.7
  ?>
6. min
  (PHP 4, PHP 5)
  min — Find lowest value
  Description
  mixed min ( array $values )
  mixed min ( mixed $value1, mixed $value2 [, mixed $value3...] )
  If the first and only parameter is an array, min() returns the lowest value in that array. If
  at least two parameters are provided, min() returns the smallest of these values.
  Note: PHP will evaluate a non-numeric string as 0 if compared to integer, but still return
  the string if it's seen as the numerically lowest value. If multiple arguments evaluate to 0,
  min() will return the lowest alphanumerical string value if any strings are given, else a
  numeric 0 is returned.
  Parameters
  values
  An array containing the values.
  Return Values
  min() returns the numerically lowest of the parameter values.
  Examples
  Example 1160. Example uses of min()
  <?php
  echo min(2, 3, 1, 6, 7); // 1
  echo min(array(2, 4, 5)); // 2

  echo min(0, 'hello');             // 0
  echo min('hello', 0);             // hello
  echo min('hello', -1);            // -1

  // With multiple arrays, min compares from left to right
  // so in our example: 2 == 2, but 4 < 5
  $val = min(array(2, 4, 8), array(2, 5, 1)); // array(2, 4, 8)

  // If both an array and non-array are given, the array
  // is never returned as it's considered the largest




Lecturer Javedkhan M. Pathan [9998099262]                                   Page 85 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
  $val = min('string', array(2, 5, 7), 42);                // string
  ?>
7. max
  (PHP 4, PHP 5)
  max — Find highest value
  Description
  mixed max ( array $values )
  mixed max ( mixed $value1, mixed $value2 [, mixed $value3...] )
  If the first and only parameter is an array, max() returns the highest value in that array. If
  at least two parameters are provided, max() returns the biggest of these values.
  Note: PHP will evaluate a non-numeric string as 0 if compared to integer, but still return
  the string if it's seen as the numerically highest value. If multiple arguments evaluate to
  0, max() will return a numeric 0 if given, else the alphabetical highest string value will
  be returned.
  Parameters
  values
  An array containing the values.
  Return Values
  max() returns the numerically highest of the parameter values.
  Examples
  Example 1159. Example uses of max()
  <?php
  echo max(1, 3, 5, 6, 7); // 7
  echo max(array(2, 4, 5)); // 5

  echo max(0, 'hello');             // 0
  echo max('hello', 0);             // hello
  echo max(-1, 'hello');            // hello

  // With multiple arrays, max compares from left to right
  // so in our example: 2 == 2, but 4 < 5
  $val = max(array(2, 4, 8), array(2, 5, 7)); // array(2, 5, 7)

  // If both an array and non-array are given, the array
  // is always returned as it's seen as the largest
  $val = max('string', array(2, 5, 7), 42);   // array(2, 5, 7)
  ?>


8. pow
  (PHP 4, PHP 5)
  pow — Exponential expression
  Description
  number pow ( number $base, number $exp )
  Returns base raised to the power of exp.
  Warning

Lecturer Javedkhan M. Pathan [9998099262]                                   Page 86 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
   In PHP 4.0.6 and earlier pow() always returned a float, and did not issue warnings.
   Parameters
   base
   The base to use
   exp
   The exponent
   Return Values
   base  raised to the power of exp. If the result can be represented as integer it will be
   returned as type integer, else it will be returned as type float. If the power cannot be
   computed FALSE will be returned instead.
   ChangeLog
   Version                                         Description
                  The function will now return integer results if possible, before this it
   Since
                  always returned a float result. For older versions, you may receive a
   4.0.6
                  bogus result for complex numbers.
   Since          PHP stops to emit a warning if the value can't be computed, it will now
   4.2.0          silently return FALSE only.
   Examples
   Example 1165. Some examples of pow()
   <?php

   var_dump(pow(2, 8)); // int(256)
   echo pow(-1, 20); // 1
   echo pow(0, 0); // 1

   echo pow(-1, 5.5); // PHP >4.0.6 NAN
   echo pow(-1, 5.5); // PHP <=4.0.6 1.#IND
   ?>
9. sqrt
   (PHP 4, PHP 5)
   sqrt — Square root
   Description
   float sqrt ( float $arg )
   Returns the square root of arg.
   Parameters
   arg
   The argument to process
   Return Values
   The square root of arg
   Examples
   Example 1170. sqrt() example


Lecturer Javedkhan M. Pathan [9998099262]                                    Page 87 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
  <?php
  // Precision depends on your precision directive
  echo sqrt(9); // 3
  echo sqrt(10); // 3.16227766 ...
  ?>
10. rand
  (PHP 4, PHP 5)
  rand — Generate a random integer
  Description
  int rand ( [int $min, int $max] )
  If called without the optional min, max arguments rand() returns a pseudo-random
  integer between 0 and RAND_MAX. If you want a random number between 5 and 15
  (inclusive), for example, use rand (5, 15).
  Note: On some platforms (such as Windows) RAND_MAX is only 32768. If you require a
  range larger than 32768, specifying min and max will allow you to create a range larger
  than RAND_MAX, or consider using mt_rand() instead.
  Note: As of PHP 4.2.0, there is no need to seed the random number generator with
  srand() or mt_srand() as this is now done automatically.
  Parameters
  min
  The lowest value to return (default: 0)
  max
  The highest value to return (default: RAND_MAX)
  Return Values
  A pseudo random value between min (or 0) and max (or RAND_MAX, inclusive).
  ChangeLog
   Version                                      Description
                 In versions before 3.0.7 the meaning of max was range. To get the same
  Since
                 results in these versions the short example should be rand (5, 11) to get a
  3.0.7
                 random number between 5 and 15.
  Examples
  Example 1167. rand() example
  <?php
  echo rand() . "\n";
  echo rand() . "\n";

  echo rand(5, 15);
  ?>
  The above example will output something similar to:
  7771
  22264
  11
 Date and Time Functions

Lecturer Javedkhan M. Pathan [9998099262]                                 Page 88 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS

       date — Format a local time/date
       getdate — Get date/time information
       checkdate — Validate a Gregorian date
       time — Return current Unix timestamp
       mktime — Get Unix timestamp for a date




date_create — Returns new DateTime object
date_date_set — Sets the date
date_default_timezone_get — Gets the default timezone used by all date/time functions in a
script
date_default_timezone_set — Sets the default timezone used by all date/time functions in a
script
date_format — Returns date formatted according to given format
date_isodate_set — Sets the ISO date
date_modify — Alters the timestamp
date_offset_get — Returns the daylight saving time offset
date_parse — Returns associative array with detailed info about given date
date_sun_info — Returns an array with information about sunset/sunrise and twilight
begin/end
date_sunrise — Returns time of sunrise for a given day and location
date_sunset — Returns time of sunset for a given day and location
date_time_set — Sets the time
date_timezone_get — Return time zone relative to given DateTime
date_timezone_set — Sets the time zone for the DateTime object
gettimeofday — Get current time
gmdate — Format a GMT/UTC date/time
gmmktime — Get Unix timestamp for a GMT date
gmstrftime — Format a GMT/UTC time/date according to locale settings
idate — Format a local time/date as integer
localtime — Get the local time
microtime — Return current Unix timestamp with microseconds
strftime — Format a local time/date according to locale settings
strptime — Parse a time/date generated with strftime()
strtotime — Parse about any English textual datetime description into a Unix timestamp
timezone_abbreviations_list — Returns associative array containing dst, offset and the
timezone name
timezone_identifiers_list — Returns numerically index array with all timezone identifiers
timezone_name_from_abbr — Returns the timezone name from abbrevation
timezone_name_get — Returns the name of the timezone
timezone_offset_get — Returns the timezone offset from GMT
timezone_open — Returns new DateTimeZone object

Lecturer Javedkhan M. Pathan [9998099262]                                Page 89 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
timezone_transitions_get — Returns all transitions for the timezone



1. date
    (PHP 4, PHP 5)
    date — Format a local time/date
    Description
    string date ( string $format [, int $timestamp] )
    Returns a string formatted according to the given format string using the given integer
    timestamp or the current time if no timestamp is given. In other words, timestamp is
    optional and defaults to the value of time().
    Parameters
    format
    The format of the outputted date string. See the formatting options below.
    Table 42. The following characters are recognized in the format parameter string
           format
                                                                                  Example
           character                            Description                       returned
                                                                                   values
             Day            ---                                                         ---
             d              Day of the month, 2 digits with leading zeros               01 to 31
                                                                                        Mon through
             D              A textual representation of a day, three letters
                                                                                        Sun
             j              Day of the month without leading zeros                      1 to 31
             l                                                                          Sunday
             (lowercase     A full textual representation of the day of the week        through
             'L')                                                                       Saturday
                                                                                        1 (for
                            ISO-8601 numeric representation of the day of the           Monday)
             N
                            week (added in PHP 5.1.0)                                   through 7 (for
                                                                                        Sunday)
                                                                                        st, nd, rd or th.
                            English ordinal suffix for the day of the month, 2
             S                                                                          Works well
                            characters
                                                                                        with j
                                                                                        0 (for Sunday)
             w              Numeric representation of the day of the week               through 6 (for
                                                                                        Saturday)
             z              The day of the year (starting from 0)                       0 through 365
                 Week       ---                                                         ---



Lecturer Javedkhan M. Pathan [9998099262]                                      Page 90 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS

       format
                                                                                  Example
       character                       Description                                returned
                                                                                   values
                                                                            Example: 42
                   ISO-8601 week number of year, weeks starting on          (the 42nd
       W
                   Monday (added in PHP 4.1.0)                              week in the
                                                                            year)
           Month   ---                                                      ---
                                                                            January
                   A full textual representation of a month, such as
       F                                                                    through
                   January or March
                                                                            December
                   Numeric representation of a month, with leading
       m                                                                    01 through 12
                   zeros
                   A short textual representation of a month, three         Jan through
       M
                   letters                                                  Dec
                   Numeric representation of a month, without
       n                                                                    1 through 12
                   leading zeros
       t           Number of days in the given month                        28 through 31
           Year    ---                                                      ---
                                                                            1 if it is a leap
       L           Whether it's a leap year                                 year, 0
                                                                            otherwise.
                   ISO-8601 year number. This has the same value as
                   Y, except that if the ISO week number (W) belongs        Examples:
       o
                   to the previous or next year, that year is used          1999 or 2003
                   instead. (added in PHP 5.1.0)
                                                                            Examples:
       Y           A full numeric representation of a year, 4 digits
                                                                            1999 or 2003
                                                                            Examples: 99
       y           A two digit representation of a year
                                                                            or 03
           Time    ---                                                      ---
       a           Lowercase Ante meridiem and Post meridiem                am or pm
       A           Uppercase Ante meridiem and Post meridiem                AM or PM
                                                                            000 through
       B           Swatch Internet time
                                                                            999
       g           12-hour format of an hour without leading zeros          1 through 12
       G           24-hour format of an hour without leading zeros          0 through 23
       h           12-hour format of an hour with leading zeros             01 through 12


Lecturer Javedkhan M. Pathan [9998099262]                          Page 91 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS

         format
                                                                                          Example
         character                            Description                                 returned
                                                                                           values
         H                24-hour format of an hour with leading zeros              00 through 23
         i                Minutes with leading zeros                                00 to 59
         s                Seconds, with leading zeros                               00 through 59
                                                                                    Example:
         u                Milliseconds (added in PHP 5.2.2)
                                                                                    54321
             Timezone     ---                                                       ---
                                                                                    Examples:
                                                                                    UTC, GMT,
         e                Timezone identifier (added in PHP 5.1.0)
                                                                                    Atlantic/Azore
                                                                                    s
                                                                                    1 if Daylight
         I (capital
                          Whether or not the date is in daylight saving time        Saving Time,
         i)
                                                                                    0 otherwise.
                                                                                    Example:
         O                Difference to Greenwich time (GMT) in hours
                                                                                    +0200
                          Difference to Greenwich time (GMT) with colon             Example:
         P
                          between hours and minutes (added in PHP 5.1.3)            +02:00
                                                                                    Examples:
         T                Timezone abbreviation
                                                                                    EST, MDT ...
                          Timezone offset in seconds. The offset for
                                                                                    -43200
         Z                timezones west of UTC is always negative, and for
                                                                                    through 50400
                          those east of UTC is always positive.
           Full
                          ---                                                       ---
         Date/Time
                                                                                    2004-02-
         c                ISO 8601 date (added in PHP 5)                            12T15:19:21+
                                                                                    00:00
                                                                                    Example: Thu,
                                                                                    21 Dec 2000
         r                » RFC 2822 formatted date
                                                                                    16:01:07
                                                                                    +0200
                          Seconds since the Unix Epoch (January 1 1970
         U                                                                          See also time()
                          00:00:00 GMT)

  Unrecognized characters in the format string will be printed as-is. The Z format will
  always return 0 when using gmdate().


Lecturer Javedkhan M. Pathan [9998099262]                                Page 92 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
  Note: Since this function only accepts integer timestamps the u format character is only
  useful when using the date_format() function with user based timestamps created with
  date_create().
  timestamp
  The optional timestamp parameter is an integer Unix timestamp that defaults to the
  current local time if a timestamp is not given. In other words, it defaults to the value of
  time().
  Return Values
  Returns a formatted date string. If a non-numeric value is used for timestamp, FALSE is
  returned and an E_WARNING level error is emitted.
  Errors/Exceptions
  Every call to a date/time function will generate a E_NOTICE if the time zone is not valid,
  and/or a E_STRICT message if using the system settings or the TZ environment variable.
  See also date_default_timezone_set()
  ChangeLog
  Version                                      Description
                The valid range of a timestamp is typically from Fri, 13 Dec 1901 20:45:54
                GMT to Tue, 19 Jan 2038 03:14:07 GMT. (These are the dates that
  5.1.0         correspond to the minimum and maximum values for a 32-bit signed
                integer). However, before PHP 5.1.0 this range was limited from 01-01-
                1970 to 19-01-2038 on some systems (e.g. Windows).
  5.1.0         Now issues the E_STRICT and E_NOTICE time zone errors.
                There are useful constants of standard date/time formats that can be used to
  5.1.1
                specify the format parameter.
  Examples
  Example 453. date() examples
  <?php
  // set the default timezone to use. Available since PHP 5.1
  date_default_timezone_set('UTC');


  // Prints something like: Monday
  echo date("l");

  // Prints something like: Monday 8th of August 2005 03:12:46 PM
  echo date('l jS \of F Y h:i:s A');

  // Prints: July 1, 2000 is on a Saturday
  echo "July 1, 2000 is on a " . date("l", mktime(0, 0, 0, 7, 1, 2000));

  /* use the constants in the format parameter */
  // prints something like: Mon, 15 Aug 2005 15:12:46 UTC
  echo date(DATE_RFC822);




Lecturer Javedkhan M. Pathan [9998099262]                                  Page 93 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
  // prints something like: 2000-07-01T00:00:00+00:00
  echo date(DATE_ATOM, mktime(0, 0, 0, 7, 1, 2000));
  ?>

  You can prevent a recognized character in the format string from being expanded by
  escaping it with a preceding backslash. If the character with a backslash is already a
  special sequence, you may need to also escape the backslash.
  Example 454. Escaping characters in date()
  <?php
  // prints something like: Wednesday the 15th
  echo date("l \\t\h\e jS");
  ?>


2. getdate
  (PHP 4, PHP 5)
  getdate — Get date/time information
  Description
  array getdate ( [int $timestamp] )
  Returns an associative array containing the date information of the timestamp, or the
  current local time if no timestamp is given.
  Parameters
  timestamp
  The optional timestamp parameter is an integer Unix timestamp that defaults to the
  current local time if a timestamp is not given. In other words, it defaults to the value of
  time().
  Return Values
  Returns an associative array of information related to the typestamp. Elements from the
  returned associative array are as follows:
  Table 43. Key elements of the returned associative array
     Key                        Description                     Example returned values
  "seconds"       Numeric representation of seconds            0 to 59
  "minutes"       Numeric representation of minutes             0 to 59
  "hours"         Numeric representation of hours               0 to 23
                  Numeric representation of the day of
  "mday"                                                        1 to 31
                  the month
                  Numeric representation of the day of          0 (for Sunday) through 6 (for
  "wday"
                  the week                                      Saturday)
  "mon"           Numeric representation of a month             1 through 12
                  A full numeric representation of a
  "year"                                                        Examples: 1999 or 2003
                  year, 4 digits
  "yday"          Numeric representation of the day of          0 through 365


Lecturer Javedkhan M. Pathan [9998099262]                                  Page 94 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS

      Key                      Description                     Example returned values
                  the year
                  A full textual representation of the
  "weekday"                                                   Sunday through Saturday
                  day of the week
                  A full textual representation of a
  "month"                                                     January through December
                  month, such as January or March
                  Seconds since the Unix Epoch,               System Dependent, typically
  0               similar to the values returned by           -2147483648 through
                  time() and used by date().                  2147483647.


  Examples
  Example 457. getdate() example
  <?php
  $today = getdate();
  print_r($today);
  ?>
  The above example will output something similar to:
  Array
  (
      [seconds]    =>   40
      [minutes]    =>   58
      [hours]      =>   21
      [mday]       =>   17
      [wday]       =>   2
      [mon]        =>   6
      [year]       =>   2003
      [yday]       =>   167
      [weekday]    =>   Tuesday
      [month]      =>   June
      [0]          =>   1055901520
  )


3. checkdate
  (PHP 4, PHP 5)
  checkdate — Validate a Gregorian date
  Description
  bool checkdate ( int $month, int $day, int $year )
  Checks the validity of the date formed by the arguments. A date is considered valid if
  each parameter is properly defined.
  Parameters
  month
  The month is between 1 and 12 inclusive.
  day



Lecturer Javedkhan M. Pathan [9998099262]                                Page 95 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
  The day is within the allowed number of days for the given month. Leap years are taken
  into consideration.
  year
  The year is between 1 and 32767 inclusive.
  Return Values
  Returns TRUE if the date given is valid; otherwise returns FALSE.
  Examples
  Example 447. checkdate() example
  <?php
  var_dump(checkdate(12, 31, 2000));
  var_dump(checkdate(2, 29, 2001));
  ?>
  The above example will output:
  bool(true)
  bool(false)
4. time
  (PHP 4, PHP 5)
  time — Return current Unix timestamp
  Description
  int time ( void )
  Returns the current time measured in the number of seconds since the Unix Epoch
  (January 1 1970 00:00:00 GMT).
  Examples
  Example 473. time() example
  <?php
  $nextWeek = time() + (7 * 24 * 60 * 60);
                     // 7 days; 24 hours; 60 mins; 60secs
  echo 'Now:       '. date('Y-m-d') ."\n";
  echo 'Next Week: '. date('Y-m-d', $nextWeek) ."\n";
  // or using strtotime():
  echo 'Next Week: '. date('Y-m-d', strtotime('+1 week')) ."\n";
  ?>
  The above example will output something similar to:
  Now:       2005-03-30
  Next Week: 2005-04-06
  Next Week: 2005-04-06

5. mktime
  (PHP 4, PHP 5)
  mktime — Get Unix timestamp for a date
  Description
  int mktime ( [int $hour [, int $minute [, int $second [, int $month [, int $day [, int $year
  [, int $is_dst]]]]]]] )


Lecturer Javedkhan M. Pathan [9998099262]                                   Page 96 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
  Returns the Unix timestamp corresponding to the arguments given. This timestamp is a
  long integer containing the number of seconds between the Unix Epoch (January 1 1970
  00:00:00 GMT) and the time specified.
  Arguments may be left out in order from right to left; any arguments thus omitted will be
  set to the current value according to the local date and time.
  Parameters
  hour
  The number of the hour.
  minute
  The number of the minute.
  second
  The number of seconds past the minute.
  month
  The number of the month.
  day
  The number of the day.
  year
  The number of the year, may be a two or four digit value, with values between 0-69
  mapping to 2000-2069 and 70-100 to 1970-2000. On systems where time_t is a 32bit
  signed integer, as most common today, the valid range for year is somewhere between
  1901 and 2038. However, before PHP 5.1.0 this range was limited from 1970 to 2038 on
  some systems (e.g. Windows).
  is_dst
  This parameter can be set to 1 if the time is during daylight savings time (DST), 0 if it is
  not, or -1 (the default) if it is unknown whether the time is within daylight savings time
  or not. If it's unknown, PHP tries to figure it out itself. This can cause unexpected (but
  not incorrect) results. Some times are invalid if DST is enabled on the system PHP is
  running on or is_dst is set to 1. If DST is enabled in e.g. 2:00, all times between 2:00
  and 3:00 are invalid and mktime() returns an undefined (usually negative) value. Some
  systems (e.g. Solaris 8) enable DST at midnight so time 0:30 of the day when DST is
  enabled is evaluated as 23:30 of the previous day.
  Note: As of PHP 5.1.0, this parameter became deprecated. As a result, the new timezone
  handling features should be used instead.
  Return Values
  mktime() returns the Unix timestamp of the arguments given. If the arguments are
  invalid, the function returns FALSE (before PHP 5.1 it returned -1).
  Errors/Exceptions
  Every call to a date/time function will generate a E_NOTICE if the time zone is not valid,
  and/or a E_STRICT message if using the system settings or the TZ environment variable.
  See also date_default_timezone_set()
  ChangeLog
  Version                                       Description
  3.0.10        Added is_dst parameter


Lecturer Javedkhan M. Pathan [9998099262]                                  Page 97 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS

  Version                                         Description
               The is_dst parameter became deprecated. Made the function return FALSE
  5.1.0        on error, instead of -1. Fixed the function to accept the year, month and
               day to be all passed as zero.
  5.1.0        Now issues the E_STRICT and E_NOTICE time zone errors.
  Examples
  Example 466. mktime() example
  mktime() is useful for doing date arithmetic and validation, as it will automatically
  calculate the correct value for out-of-range input. For example, each of the following
  lines produces the string "Jan-01-1998".
  <?php
  echo date("M-d-Y",      mktime(0,    0,   0,   12, 32, 1997));
  echo date("M-d-Y",      mktime(0,    0,   0,   13, 1, 1997));
  echo date("M-d-Y",      mktime(0,    0,   0,   1, 1, 1998));
  echo date("M-d-Y",      mktime(0,    0,   0,   1, 1, 98));
  ?>

  Example 467. Last day of next month
  The last day of any given month can be expressed as the "0" day of the next month, not
  the -1 day. Both of the following examples will produce the string "The last day in Feb
  2000 is: 29".
  <?php
  $lastday = mktime(0, 0,       0,   3, 0, 2000);
  echo strftime("Last day       in   Feb 2000 is: %d", $lastday);
  $lastday = mktime(0, 0,       0,   4, -31, 2000);
  echo strftime("Last day       in   Feb 2000 is: %d", $lastday);
  ?>




 Array Function:-
  count — Count elements in an array, or properties in an object
   list — Assign variables as if they were an array
   in_array — Checks if a value exists in an array
   current — Return the current element in an array
  next — Advance the internal array pointer of an array
  prev — Rewind the internal array pointer
  end — Set the internal pointer of an array to its last element
  each — Return the current key and value pair from an array and advance the array cursor
  sort — Sort an array
  rsort — Sort an array in reverse order
  asort — Sort an array and maintain index association
  arsort — Sort an array in reverse order and maintain index association


Lecturer Javedkhan M. Pathan [9998099262]                                Page 98 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
  array_merge — Merge one or more arrays
  array_reverse — Return an array with elements in reverse order



  array_change_key_case — Changes all keys in an array
  array_chunk — Split an array into chunks
  array_combine — Creates an array by using one array for keys and another for its values
  array_count_values — Counts all the values of an array
  array_diff_assoc — Computes the difference of arrays with additional index check
  array_diff_key — Computes the difference of arrays using keys for comparison
  array_diff_uassoc — Computes the difference of arrays with additional index check
  which is performed by a user supplied callback function
  array_diff_ukey — Computes the difference of arrays using a callback function on the
  keys for comparison
  array_diff — Computes the difference of arrays
  array_fill_keys — Fill an array with values, specifying keys
  array_fill — Fill an array with values
  array_filter — Filters elements of an array using a callback function
  array_flip — Exchanges all keys with their associated values in an array
  array_intersect_assoc — Computes the intersection of arrays with additional index check
  array_intersect_key — Computes the intersection of arrays using keys for comparison
  array_intersect_uassoc — Computes the intersection of arrays with additional index
  check, compares indexes by a callback function
  array_intersect_ukey — Computes the intersection of arrays using a callback function on
  the keys for comparison
  array_intersect — Computes the intersection of arrays
  array_key_exists — Checks if the given key or index exists in the array
  array_keys — Return all the keys of an array
  array_map — Applies the callback to the elements of the given arrays
  array_merge_recursive — Merge two or more arrays recursively

  array_multisort — Sort multiple or multi-dimensional arrays
  array_pad — Pad array to the specified length with a value
  array_pop — Pop the element off the end of array
  array_product — Calculate the product of values in an array
  array_push — Push one or more elements onto the end of array
  array_rand — Pick one or more random entries out of an array
  array_reduce — Iteratively reduce the array to a single value using a callback function
  array_search — Searches the array for a given value and returns the corresponding key if
  successful
  array_shift — Shift an element off the beginning of array
  array_slice — Extract a slice of the array
  array_splice — Remove a portion of the array and replace it with something else
  array_sum — Calculate the sum of values in an array

Lecturer Javedkhan M. Pathan [9998099262]                               Page 99 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
  array_udiff_assoc — Computes the difference of arrays with additional index check,
  compares data by a callback function
  array_udiff_uassoc — Computes the difference of arrays with additional index check,
  compares data and indexes by a callback function
  array_udiff — Computes the difference of arrays by using a callback function for data
  comparison
  array_uintersect_assoc — Computes the intersection of arrays with additional index
  check, compares data by a callback function
  array_uintersect_uassoc — Computes the intersection of arrays with additional index
  check, compares data and indexes by a callback functions
  array_uintersect — Computes the intersection of arrays, compares data by a callback
  function
  array_unique — Removes duplicate values from an array
  array_unshift — Prepend one or more elements to the beginning of an array
  array_values — Return all the values of an array
  array_walk_recursive — Apply a user function recursively to every member of an array
  array_walk — Apply a user function to every member of an array
  array — Create an array
  compact — Create array containing variables and their values
  extract — Import variables into the current symbol table from an array
  key — Fetch a key from an associative array
  krsort — Sort an array by key in reverse order
  ksort — Sort an array by key
  natcasesort — Sort an array using a case insensitive "natural order" algorithm
  natsort — Sort an array using a "natural order" algorithm
  pos — Alias of current()
  range — Create an array containing a range of elements
  reset — Set the internal pointer of an array to its first element

  shuffle — Shuffle an array
  sizeof — Alias of count()
  uasort — Sort an array with a user-defined comparison function and maintain index
  association
  uksort — Sort an array by keys using a user-defined comparison function
  usort — Sort an array by values using a user-defined comparison function



1. count
  (PHP 4, PHP 5)
  count — Count elements in an array, or properties in an object
  Description
  int count ( mixed $var [, int $mode] )


Lecturer Javedkhan M. Pathan [9998099262]                             Page 100 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
  Returns the number of elements in var, which is typically an array, since anything else
  will have one element.
  For objects, if you have SPL installed, you can hook into count() by implementing
  interface Countable. The interface has exactly one method, count(), which returns the
  return value for the count() function.
  If var is not an array or an object with implemented Countable interface, 1 will be
  returned. There is one exception, if var is NULL, 0 will be returned.
  Note: The optional mode parameter is available as of PHP 4.2.0.
  If the optional mode parameter is set to COUNT_RECURSIVE (or 1), count() will
  recursively count the array. This is particularly useful for counting all the elements of a
  multidimensional array. The default value for mode is 0. count() does not detect infinite
  recursion.
  Caution
  count() may return 0 for a variable that isn't set, but it may also return 0 for a variable
  that has been initialized with an empty array. Use isset() to test if a variable is set.
  Please see the Array section of the manual for a detailed explanation of how arrays are
  implemented and used in PHP.
  Example 305. count() example
  <?php
  $a[0] = 1;
  $a[1] = 3;
  $a[2] = 5;
  $result = count($a);
  // $result == 3

  $b[0] = 7;
  $b[5] = 9;
  $b[10] = 11;
  $result = count($b);
  // $result == 3

  $result = count(null);
  // $result == 0

  $result = count(false);
  // $result == 1
  ?>

  Example 306. Recursive count() example (PHP >= 4.2.0)
  <?php
  $food = array('fruits' => array('orange', 'banana', 'apple'),
                'veggie' => array('carrot', 'collard', 'pea'));

  // recursive count
  echo count($food, COUNT_RECURSIVE); // output 8

  // normal count
  echo count($food); // output 2

  ?>


Lecturer Javedkhan M. Pathan [9998099262]                                  Page 101 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS

2. list
   (PHP 4, PHP 5)
   list — Assign variables as if they were an array
   Description
   void list ( mixed $varname, mixed $... )
   Like array(), this is not really a function, but a language construct. list() is used to assign
   a list of variables in one operation.
   Note: list() only works on numerical arrays and assumes the numerical indices start at 0.
   Example 318. list() examples
   <?php

   $info = array('coffee', 'brown', 'caffeine');

   // Listing all the variables
   list($drink, $color, $power) = $info;
   echo "$drink is $color and $power makes it special.\n";

   // Listing some of them
   list($drink, , $power) = $info;
   echo "$drink has $power.\n";

   // Or let's skip to only the third one
   list( , , $power) = $info;
   echo "I need $power!\n";

   // list() doesn't work with strings
   list($bar) = "abcde";
   var_dump($bar); // NULL
   ?>

   Example 319. An example use of list()
   <table>
    <tr>
     <th>Employee name</th>
     <th>Salary</th>
    </tr>

   <?php

   $result = mysql_query("SELECT id, name, salary FROM employees", $conn);
   while (list($id, $name, $salary) = mysql_fetch_row($result)) {
       echo " <tr>\n" .
             " <td><a href=\"info.php?id=$id\">$name</a></td>\n" .
             " <td>$salary</td>\n" .
             " </tr>\n";
   }

   ?>

   </table>


Lecturer Javedkhan M. Pathan [9998099262]                                      Page 102 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS

  Warning
  list() assigns the values starting with the right-most parameter. If you are using plain
  variables, you don't have to worry about this. But if you are using arrays with indices
  you usually expect the order of the indices in the array the same you wrote in the list()
  from left to right; which it isn't. It's assigned in the reverse order.
  Example 320. Using list() with array indices
  <?php

  $info = array('coffee', 'brown', 'caffeine');

  list($a[0], $a[1], $a[2]) = $info;

  var_dump($a);

  ?>
  Gives the following output (note the order of the elements compared in which order they
  were written in the list() syntax):
  array(3) {
    [2]=>
    string(8) "caffeine"
    [1]=>
    string(5) "brown"
    [0]=>
    string(6) "coffee"
  }


3. in_array
  (PHP 4, PHP 5)
  in_array — Checks if a value exists in an array
  Description
  bool in_array ( mixed $needle, array $haystack [, bool $strict] )
  Searches haystack for needle and returns TRUE if it is found in the array, FALSE
  otherwise.
  If the third parameter strict is set to TRUE then the in_array() function will also check
  the types of the needle in the haystack.
  Note: If needle is a string, the comparison is done in a case-sensitive manner.
  Note: In PHP versions before 4.2.0 needle was not allowed to be an array.
  Example 312. in_array() example
  <?php
  $os = array("Mac", "NT", "Irix", "Linux");
  if (in_array("Irix", $os)) {
      echo "Got Irix";
  }
  if (in_array("mac", $os)) {
      echo "Got mac";




Lecturer Javedkhan M. Pathan [9998099262]                                  Page 103 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
  }
  ?>
  The second condition fails because in_array() is case-sensitive, so the program above
  will display:
  Got Irix

4. current
  (PHP 4, PHP 5)
  current — Return the current element in an array
  Description
  mixed current ( array &$array )
  Every array has an internal pointer to its "current" element, which is initialized to the
  first element inserted into the array.
  The current() function simply returns the value of the array element that's currently
  being pointed to by the internal pointer. It does not move the pointer in any way. If the
  internal pointer points beyond the end of the elements list, current() returns FALSE.
  Warning
  This function may return Boolean FALSE, but may also return a non-Boolean value
  which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more
  information. Use the === operator for testing the return value of this function.
  Note: You won't be able to distinguish the end of an array from a boolean FALSE
  element. To properly traverse an array which may contain FALSE elements, see the
  each() function.
  Example 307. Example use of current() and friends
  <?php
  $transport = array('foot', 'bike', 'car', 'plane');
  $mode = current($transport); // $mode = 'foot';
  $mode = next($transport);    // $mode = 'bike';
  $mode = current($transport); // $mode = 'bike';
  $mode = prev($transport);    // $mode = 'foot';
  $mode = end($transport);     // $mode = 'plane';
  $mode = current($transport); // $mode = 'plane';
  ?>

5. next
  (PHP 4, PHP 5, PECL axis2:0.1.0-0.1.1 xmlreader:1.0-1.0.1)
  next — Advance the internal array pointer of an array
  Description
  mixed next ( array &$array )
  Returns the array value in the next place that's pointed to by the internal array pointer, or
  FALSE if there are no more elements.
  next() behaves like current(), with one difference. It advances the internal array pointer
  one place forward before returning the element value. That means it returns the next



Lecturer Javedkhan M. Pathan [9998099262]                                   Page 104 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
  array value and advances the internal array pointer by one. If advancing the internal
  array pointer results in going beyond the end of the element list, next() returns FALSE.
  Warning
  This function may return Boolean FALSE, but may also return a non-Boolean value
  which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more
  information. Use the === operator for testing the return value of this function.
  Note: You won't be able to distinguish the end of an array from a boolean FALSE
  element. To properly traverse an array which may contain FALSE elements, see the
  each() function.
  Example 323. Example use of next() and friends
  <?php
  $transport = array('foot', 'bike', 'car', 'plane');
  $mode = current($transport); // $mode = 'foot';
  $mode = next($transport);    // $mode = 'bike';
  $mode = next($transport);    // $mode = 'car';
  $mode = prev($transport);    // $mode = 'bike';
  $mode = end($transport);     // $mode = 'plane';
  ?>


6. prev
  (PHP 4, PHP 5)
  prev — Rewind the internal array pointer
  Description
  mixed prev ( array &$array )
  Returns the array value in the previous place that's pointed to by the internal array
  pointer, or FALSE if there are no more elements.
  Warning
  This function may return Boolean FALSE, but may also return a non-Boolean value
  which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more
  information. Use the === operator for testing the return value of this function.
  Note: You won't be able to distinguish the beginning of an array from a boolean FALSE
  element. To properly traverse an array which may contain FALSE elements, see the
  each() function.
  prev() behaves just like next(), except it rewinds the internal array pointer one place
  instead of advancing it.
  Example 324. Example use of prev() and friends
  <?php
  $transport = array('foot', 'bike', 'car', 'plane');
  $mode = current($transport); // $mode = 'foot';
  $mode = next($transport);    // $mode = 'bike';
  $mode = next($transport);    // $mode = 'car';
  $mode = prev($transport);    // $mode = 'bike';
  $mode = end($transport);     // $mode = 'plane';
  ?>




Lecturer Javedkhan M. Pathan [9998099262]                                Page 105 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS

7. end
  (PHP 4, PHP 5)
  end — Set the internal pointer of an array to its last element
  Description
  mixed end ( array &$array )
  end() advances array's internal pointer to the last element, and returns its value.
  Example 310. A simple end() example
  <?php

  $fruits = array('apple', 'banana', 'cranberry');
  echo end($fruits); // cranberry
  ?>


8. each
  (PHP 4, PHP 5)
  each — Return the current key and value pair from an array and advance the array cursor
  Description
  array each ( array &$array )
  Returns the current key and value pair from the array array and advances the array
  cursor. This pair is returned in a four-element array, with the keys 0, 1, key, and value.
  Elements 0 and key contain the key name of the array element, and 1 and value contain
  the data.
  If the internal pointer for the array points past the end of the array contents, each()
  returns FALSE.
  Example 308. each() examples
  <?php
  $foo = array("bob", "fred", "jussi", "jouni", "egon", "marliese");
  $bar = each($foo);
  print_r($bar);
  ?>
  $bar now contains the following key/value pairs:
  Array
  (
      [1] => bob
      [value] => bob
      [0] => 0
      [key] => 0
  )



  <?php
  $foo = array("Robert" => "Bob", "Seppo" => "Sepi");
  $bar = each($foo);
  print_r($bar);
  ?>



Lecturer Javedkhan M. Pathan [9998099262]                                  Page 106 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
    $bar now contains the following key/value pairs:
    Array
    (
        [1] => Bob
        [value] => Bob
        [0] => Robert
        [key] => Robert
    )


9. sort
    (PHP 4, PHP 5)
    sort — Sort an array
    Description
    bool sort ( array &$array [, int $sort_flags] )
    This function sorts an array. Elements will be arranged from lowest to highest when this
    function has completed.
    Note: This function assigns new keys for the elements in array. It will remove any
    existing keys you may have assigned, rather than just reordering the keys.
    Returns TRUE on success or FALSE on failure.
    Example 329. sort() example
    <?php

    $fruits = array("lemon", "orange", "banana", "apple");
    sort($fruits);
    foreach ($fruits as $key => $val) {
        echo "fruits[" . $key . "] = " . $val . "\n";
    }

    ?>
    The above example will output:
    fruits[0]   =   apple
    fruits[1]   =   banana
    fruits[2]   =   lemon
    fruits[3]   =   orange




    The fruits have been sorted in alphabetical order.
    The optional second parameter sort_flags may be used to modify the sorting behavior
    using these values:
    Sorting type flags:
      SORT_REGULAR - compare items normally (don't change types)
      SORT_NUMERIC - compare items numerically
      SORT_STRING - compare items as strings




Lecturer Javedkhan M. Pathan [9998099262]                                 Page 107 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
      SORT_LOCALE_STRING - compare items as strings, based on the current locale. Added
    in PHP 4.4.0 and 5.0.2. Before PHP 6, it uses the system locale, which can be changed
    using setlocale(). Since PHP 6, you must use the i18n_loc_set_default() function.
10. rsort
    (PHP 4, PHP 5)
    rsort — Sort an array in reverse order
    Description
    bool rsort ( array &$array [, int $sort_flags] )
    This function sorts an array in reverse order (highest to lowest).
    Note: This function assigns new keys for the elements in array. It will remove any
    existing keys you may have assigned, rather than just reordering the keys.
    Returns TRUE on success or FALSE on failure.
    Example 327. rsort() example
    <?php
    $fruits = array("lemon", "orange", "banana", "apple");
    rsort($fruits);
    foreach ($fruits as $key => $val) {
        echo "$key = $val\n";
    }
    ?>
    The above example will output:
    0   =   orange
    1   =   lemon
    2   =   banana
    3   =   apple




    The fruits have been sorted in reverse alphabetical order.
    You may modify the behavior of the sort using the optional parameter sort_flags,
11. asort
    (PHP 4, PHP 5)
    asort — Sort an array and maintain index association
    Description
    bool asort ( array &$array [, int $sort_flags] )
    This function sorts an array such that array indices maintain their correlation with the
    array elements they are associated with. This is used mainly when sorting associative
    arrays where the actual element order is significant.
    Returns TRUE on success or FALSE on failure.
    Example 303. asort() example
    <?php
    $fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" =
    > "apple");
    asort($fruits);
    foreach ($fruits as $key => $val) {


Lecturer Javedkhan M. Pathan [9998099262]                                    Page 108 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
           echo "$key = $val\n";
  }
  ?>
  The above example will output:
  c    =   apple
  b    =   banana
  d    =   lemon
  a    =   orange

12. arsort
  (PHP 4, PHP 5)
  arsort — Sort an array in reverse order and maintain index association
  Description
  bool arsort ( array &$array [, int $sort_flags] )
  This function sorts an array such that array indices maintain their correlation with the
  array elements they are associated with. This is used mainly when sorting associative
  arrays where the actual element order is significant.
  Returns TRUE on success or FALSE on failure.
  Example 302. arsort() example
  <?php
  $fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" =
  > "apple");
  arsort($fruits);
  foreach ($fruits as $key => $val) {
      echo "$key = $val\n";
  }
  ?>
  The above example will output:
  a    =   orange
  d    =   lemon
  b    =   banana
  c    =   apple
  The fruits have been sorted in reverse alphabetical order, and the index associated with
  each element has been maintained.
13. array_merge
  (PHP 4, PHP 5)
  array_merge — Merge one or more arrays
  Description
  array array_merge ( array $array1 [, array $array2 [, array $...]] )
  array_merge() merges the elements of one or more arrays together so that the values of
  one are appended to the end of the previous one. It returns the resulting array.
  If the input arrays have the same string keys, then the later value for that key will
  overwrite the previous one. If, however, the arrays contain numeric keys, the later value
  will not overwrite the original value, but will be appended.



Lecturer Javedkhan M. Pathan [9998099262]                                  Page 109 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
  If only one array is given and the array is numerically indexed, the keys get reindexed in
  a continuous way.
  Example 267. array_merge() example
  <?php
  $array1 = array("color" => "red", 2, 4);
  $array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4
  );
  $result = array_merge($array1, $array2);
  print_r($result);
  ?>
  The above example will output:
  Array
  (
      [color] => green
      [0] => 2
      [1] => 4
      [2] => a
      [3] => b
      [shape] => trapezoid
      [4] => 4
  )

  Example 268. Simple array_merge() example
  <?php
  $array1 = array();
  $array2 = array(1 => "data");
  $result = array_merge($array1, $array2);
  ?>
  Don't forget that numeric keys will be renumbered!
  Array
  (
      [0] => data
  )
  If you want to completely preserve the arrays and just want to append them to each other
  (not overwriting the previous keys), use the + operator:
  <?php
  $array1 = array();
  $array2 = array(1 => "data");
  $result = $array1 + $array2;
  ?>
  The numeric key will be preserved and thus the association remains.
  Array
  (
      [1] => data
  )

  Warning
  The behavior of array_merge() was modified in PHP 5. Unlike PHP 4, array_merge()
  now only accepts parameters of type array. However, you can use typecasting to merge
  other types. See the example below for details.
  Example 269. array_merge() PHP 5 example

Lecturer Javedkhan M. Pathan [9998099262]                                 Page 110 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
  <?php
  $beginning = 'foo';
  $end = array(1 => 'bar');
  $result = array_merge((array)$beginning, (array)$end);
  print_r($result);
  ?>
  The above example will output:
  Array
  (
      [0] => foo
      [1] => bar
  )
14. array_reverse
  (PHP 4, PHP 5)
  array_reverse — Return an array with elements in reverse order
  Description
  array array_reverse ( array $array [, bool $preserve_keys] )
  array_reverse() takes input array and returns a new array with the order of the
  elements reversed, preserving the keys if preserve_keys is TRUE.
  Example 280. array_reverse() example
  <?php
  $input = array("php", 4.0, array("green", "red"));
  $result = array_reverse($input);
  $result_keyed = array_reverse($input, true);
  ?>
  This makes both $result and $result_keyed have the same elements, but note the
  difference between the keys. The printout of $result and $result_keyed will be:
  Array
  (
      [0] => Array
          (
              [0] => green
              [1] => red
          )

      [1] => 4
      [2] => php
  )
  Array
  (
      [2] => Array
          (
              [0] => green
              [1] => red
          )

      [1] => 4
      [0] => php
  )
  Note: The second parameter was added in PHP 4.0.3.


Lecturer Javedkhan M. Pathan [9998099262]                               Page 111 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS

 File Handling function:-
fopen — Opens file or URL
fread — Binary-safe file read
fwrite — Binary-safe file write
fclose — Closes an open file pointer
file_exists — Checks whether a file or directory exists
is_readable — Tells whether the filename is readable

basename — Returns filename component of path
chgrp — Changes file group
chmod — Changes file mode
chown — Changes file owner
clearstatcache — Clears file status cache
copy — Copies file
delete — See unlink() or unset()
dirname — Returns directory name component of path
disk_free_space — Returns available space in directory
disk_total_space — Returns the total size of a directory
diskfreespace — Alias of disk_free_space()
feof — Tests for end-of-file on a file pointer
fflush — Flushes the output to a file
fgetc — Gets character from file pointer
fgetcsv — Gets line from file pointer and parse for CSV fields
fgets — Gets line from file pointer
fgetss — Gets line from file pointer and strip HTML tags
file_get_contents — Reads entire file into a string
file_put_contents — Write a string to a file
file — Reads entire file into an array
fileatime — Gets last access time of file
filectime — Gets inode change time of file
filegroup — Gets file group
fileinode — Gets file inode
filemtime — Gets file modification time
fileowner — Gets file owner
fileperms — Gets file permissions
filesize — Gets file size
filetype — Gets file type
flock — Portable advisory file locking
fnmatch — Match filename against a pattern
fpassthru — Output all remaining data on a file pointer
fputcsv — Format line as CSV and write to file pointer
fputs — Alias of fwrite()
fscanf — Parses input from a file according to a format
fseek — Seeks on a file pointer

Lecturer Javedkhan M. Pathan [9998099262]                        Page 112 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
fstat — Gets information about a file using an open file pointer
ftell — Tells file pointer read/write position
ftruncate — Truncates a file to a given length
glob — Find pathnames matching a pattern
is_dir — Tells whether the filename is a directory
is_executable — Tells whether the filename is executable
is_file — Tells whether the filename is a regular file
is_link — Tells whether the filename is a symbolic link
is_uploaded_file — Tells whether the file was uploaded via HTTP POST
is_writable — Tells whether the filename is writable
is_writeable — Alias of is_writable()
lchgrp — Changes group ownership of symlink
lchown — Changes user ownership of symlink
link — Create a hard link
linkinfo — Gets information about a link
lstat — Gives information about a file or symbolic link
mkdir — Makes directory
move_uploaded_file — Moves an uploaded file to a new location
parse_ini_file — Parse a configuration file
pathinfo — Returns information about a file path
pclose — Closes process file pointer
popen — Opens process file pointer
readfile — Outputs a file
readlink — Returns the target of a symbolic link
realpath — Returns canonicalized absolute pathname
rename — Renames a file or directory
rewind — Rewind the position of a file pointer
rmdir — Removes directory
set_file_buffer — Alias of stream_set_write_buffer()
stat — Gives information about a file
symlink — Creates a symbolic link
tempnam — Create file with unique file name
tmpfile — Creates a temporary file
touch — Sets access and modification time of file
umask — Changes the current umask
unlink — Deletes a file




Lecturer Javedkhan M. Pathan [9998099262]                              Page 113 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS


 Miscellaneous Function:-
  constant — Returns the value of a constant
  define — Defines a named constant
  die — Equivalent to exit()
  Network Functions
  header — Send a raw HTTP header



  connection_aborted — Check whether client disconnected
  connection_status — Returns connection status bitfield
  connection_timeout — Check if the script timed out
  defined — Checks whether a given named constant exists
  die — Equivalent to exit()
  eval — Evaluate a string as PHP code
  exit — Output a message and terminate the current script
  get_browser — Tells what the user's browser is capable of
  __halt_compiler — Halts the compiler execution
  highlight_file — Syntax highlighting of a file
  highlight_string — Syntax highlighting of a string
  ignore_user_abort — Set whether a client disconnect should abort script execution
  pack — Pack data into binary string
  php_check_syntax — Check the PHP syntax of (and execute) the specified file
  php_strip_whitespace — Return source with stripped comments and whitespace
  show_source — Alias of highlight_file()
  sleep — Delay execution
  sys_getloadavg — Gets system load average
  time_nanosleep — Delay for a number of seconds and nanoseconds
  time_sleep_until — Make the script sleep until the specified time
  uniqid — Generate a unique ID
  unpack — Unpack data from binary string
  usleep — Delay execution in microseconds
1. define
  (PHP 4, PHP 5)
  define — Defines a named constant
  Description
  bool define ( string $name, mixed $value [, bool $case_insensitive] )
  Defines a named constant at runtime.
  Parameters
  name
  The name of the constant.
  value


Lecturer Javedkhan M. Pathan [9998099262]                                 Page 114 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
  The value of the constant; only scalar and null values are allowed. Scalar values are
  integer, float, string or boolean values.
  case_insensitive
  If set to TRUE, the constant
                            will be defined case-insensitive. The default behaviour is
  case-sensitive; i.e. CONSTANT and Constant represent different values.
  Return Values
  Returns TRUE on success or FALSE on failure.
  Examples
  Example 1361. Defining Constants
  <?php
  define("CONSTANT", "Hello world.");
  echo CONSTANT; // outputs "Hello world."
  echo Constant; // outputs "Constant" and issues a notice.

  define("GREETING", "Hello you.", true);
  echo GREETING; // outputs "Hello you."
  echo Greeting; // outputs "Hello you."

  ?>
2. constant
  (PHP 4 >= 4.0.4, PHP 5)
  constant — Returns the value of a constant
  Description
  mixed constant ( string $name )
  Return the value of the constant indicated by name.
  constant() is useful if you need to retrieve the value of a constant, but do not know its
  name. I.e. it is stored in a variable or returned by a function.
  This function works also with class constants.
  Parameters
  name
  The constant name.
  Return Values
  Returns the value of the constant, or NULL if the constant is not defined.
  Examples
  Example 1360. constant() example
  <?php

  define("MAXSIZE", 100);

  echo MAXSIZE;
  echo constant("MAXSIZE"); // same thing as the previous line

  ?>




Lecturer Javedkhan M. Pathan [9998099262]                                  Page 115 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS

  3. header
  (PHP 4, PHP 5)
  header — Send a raw HTTP header
  Description
  void header ( string $string [, bool $replace [, int $http_response_code]] )
  header() is used to send a raw HTTP header. See the » HTTP/1.1 specification for more
  information on HTTP headers.
  Remember that header() must be called before any actual output is sent, either by
  normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read
  code with include(), or require(), functions, or another file access function, and have
  spaces or empty lines that are output before header() is called. The same problem exists
  when using a single PHP/HTML file.
  <html>
  <?php
  /* This will give an error. Note the output
   * above, which is before the header() call */
  header('Location: http://www.example.com/');
  ?>
  Parameters
  string
  The header string.
  There are two special-case header calls. The first is a header that starts with the string
  "HTTP/" (case is not significant), which will be used to figure out the HTTP status code
  to send. For example, if you have configured Apache to use a PHP script to handle
  requests for missing files (using the ErrorDocument directive), you may want to make
  sure that your script generates the proper status code.
  <?php
  header("HTTP/1.0 404 Not Found");
  ?>
  The second special case is the "Location:" header. Not only does it send this header back
  to the browser, but it also returns a REDIRECT (302) status code to the browser unless
  some 3xx status code has already been set.
  <?php
  header("Location: http://www.example.com/"); /* Redirect browser */

  /* Make sure that code below does not get executed when we redirect. */
  exit;
  ?>
  replace
  The optional replace parameter indicates whether the header should replace a previous
  similar header, or add a second header of the same type. By default it will replace, but if
  you pass in FALSE as the second argument you can force multiple headers of the same
  type. For example:
  <?php
  header('WWW-Authenticate: Negotiate');
  header('WWW-Authenticate: NTLM', false);
  ?>


Lecturer Javedkhan M. Pathan [9998099262]                                  Page 116 of 117
SHRI C.J.PATEL COLLEGE OF COMPUTER STUDIES, VISNAGAR
BCA 302: BUILDING APPLICATION USING ASP/PHP
                UNIT:-2 PHP 17 MARKS
  http_response_code
  Forces the HTTP response code to the specified value.
  Return Values
  No value is returned.
  ChangeLog
    Version                                          Description
  4.4.2 and        This function now prevents more than one header to be sent at once as
  5.1.2            a protection against header injection attacks.
  4.3.0            The http_response_code parameter was added.
  4.0.4            The replace parameter was added.
  Examples
  Example 1609. Download dialog
  If you want the user to be prompted to save the data you are sending, such as a generated
  PDF file, you can use the » Content-Disposition header to supply a recommended
  filename and force the browser to display the save dialog.
  <?php
  // We'll be outputting a PDF
  header('Content-type: application/pdf');

  // It will be called downloaded.pdf
  header('Content-Disposition: attachment; filename="downloaded.pdf"');

  // The PDF source is in original.pdf
  readfile('original.pdf');
  ?>


  4. DIE
  (PHP 4, PHP 5)
  die — Equivalent to exit()
  Description
  This language construct is equivalent to exit().




Lecturer Javedkhan M. Pathan [9998099262]                                Page 117 of 117

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:30
posted:8/31/2011
language:English
pages:117