Blog

  • Variables

    A variable in PHP is a named memory location that holds data belonging to one of the data types.

    • PHP uses the convention of prefixing a dollar sign ($) to the name of a variable.
    • Variable names in PHP are 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 per the naming convention, “$name”, “$rate_of_int”, “$Age”, “$mark1” are examples of valid variable names in PHP.
    • Invalid variable names: “name” (not having $ prefix), “$rate of int” (whitespace not allowed), “$Age#1” (invalid character #), “$11” (name not starting with alphabet).

    Variables are assigned with the “=” operator, with the variable on the left hand side and the expression to be evaluated on the right.

    No Need to Specify the Type of a Variable

    PHP is a dynamically typed language. There is no need to specify the type of a variable. On the contrary, the type of a variable is decided by the value assigned to it. The value of a variable is the value of its most recent assignment.

    Take a look at this following example −

    <?php
       $x = 10;
       echo "Data type of x: " . gettype($x) . "\n";
    
       $x = 10.55;
       echo "Data type of x now: " . gettype($x) . "";
    ?>

    It will produce the following output −

    Data type of x: integer
    Data type of x now: double
    

    Automatic Type Conversion of Variables

    PHP does a good job of automatically converting types from one to another when necessary. In the following code, PHP converts a string variable “y” to “int” to perform addition with another integer variable and print 30 as the result.

    Take a look at this following example −

    <?php
       $x = 10;
       $y = "20";
    
       echo "x + y is: ", $x+$y;
    ?>

    It will produce the following output −

    x + y is: 30
    

    Variables are Assigned by Value

    In PHP, variables are always assigned by value. If an expression is assigned to a variable, the value of the original expression is copied into it. If the value of any of the variables in the expression changes after the assignment, it doesn’t have any effect on the assigned value.

    <?php
       $x = 10;
       $y = 20;
       $z = $x+$y;
       echo "(before) z = ". $z . "\n";
    
       $y=5;
       echo "(after) z = ". $z . "";
    ?>

    It will produce the following output −

    (before) z = 30
    (after) z = 30
    

    Assigning Values to PHP Variables by Reference

    You can also use the way to assign values to PHP variables by reference. In this case, the new variable simply references or 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).

    Take a look at this following example −

    <?php
       $x = 10;
       $y = &$x;
       $z = $x+$y;
       echo "x=". $x . " y=" . $y . " z = ". $z . "\n";
    
       $y=20;
       $z = $x+$y;
       echo "x=". $x . " y=" . $y . " z = ". $z . "";
    ?>

    It will produce the following output −

    x=10 y=10 z = 20
    x=20 y=20 z = 40
    

    Variable Scope

    Scope can be defined as the range of availability a variable has to the program in which it is declared. PHP variables can be one of four scope types −

    • Local Variables
    • Global Variables
    • Static Variables
    • Function Parameters

    Variable Naming

    Rules for naming a variable is −

    • Variable names must begin with a letter or underscore character.
    • A variable name can consist of numbers, letters, underscores but you cannot use characters like + , – , % , ( , ) . & , etc

    There is no size limit for variables.

  • Comments

    A comment in any computer program (such as a PHP program) is a certain explanatory text that is ignored by the language compiler/interpreter. Its purpose is to help the user understand the logic used in the program algorithm.

    Although placing comments in the code is not essential, it is a highly recommended practice. The comments also serve as program documentation. Comments are also useful when the code needs to be debugged and modified.

    There are two commenting formats in PHP −

    • Single-line Comments
    • Multi-line Comments

    Single-line Comments

    They are generally used for short explanations or notes relevant to the local code. PHP uses two notations for inserting a single-line comment in a program.

    Single-line Comments Using “#”

    A line in PHP code starting with the “#” symbol is treated as a single-line comment.

    <?php
       # Single line comment starting with # symbol
       echo 'Hello World';
    ?>

    Single-line Comments Using “//”

    PHP also supports C style of single-line comments with “//” symbol. A line starting with double oblique symbol is treated as a comment.

    <?php
       // Single line comment starting with // symbol
       echo 'Hello World';
    ?>

    A comment that starts with the symbol “#” or “//” need not be closed. The effect of these symbols last till the end of the physical line.

    In other words, the PHP parser will treat the next line as a PHP statement and not as a comment even if there is no closing comment marker.

    Multi-line Comments

    Multi-line comments are generally used to provide pseudocode algorithms and more detailed explanations when necessary.

    The multiline style of commenting is the same as in C. One or more lines embedded inside the “/*” and “*/” symbols are treated as a comment.

    Example of Multi-line Comment in PHP

    Here is the example of a multi-line comment.

    <?php
    
       /* This is a multiline comment example
       program to add two numbers
       Variables used - $x for first number, 
       $y for second number */
       
       $x=10;
       $y=20;
       print "Total = ". $x+$y;
    ?>

    Note that you can put even a single line inside the “/* .. */” symbols. However, if there is a “/*” symbol in the program, it must have a closing end-of comment marker “*/”. If not, an error will be displayed as follows −

    PHP Parse error:  Unterminated comment starting line 3 in /home/cg/root/65ded9eeb52fc/main.php on line 3
  • Hello World

    Conventionally, learners write a “Hello World” program as their first program when learning a new language or a framework. The objective is to verify if the software to be used has been installed correctly and is working as expected. To run a Hello World program in PHP, you should have installed the Apache server along with PHP module on the operating system you are using.

    PHP is a server-side programming language. The PHP code must be available in the document root of the web server. The web server document root is the root directory of the web server running on your system. The documents under this root are accessible to any system connected to the web server (provided the user has permissions). If a file is not under this root directory, then it cannot be accessed through the web server.

    In this tutorial, we are using XAMPP server software for writing PHP code. The default document root directory is typically “C:\xampp\htdocs\” on Windows and “/opt/lamp/htdocs/” on Linux. However, you can change the default document root by modifying the DocumentRoot setting in Apache server’s configuration file “httpd.conf”.

    While on a Windows operating system, start the Apache server from the XAMPP control panel.

    PHP Hello World

    Browse to the “htdocs” directory. Save the following script as “hello.php” in it.

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

    Open a new tab in your browser and enter http://localhost/hello.php as the URL. You should see the “Hello World” message in the browser window.

    A PHP script may contain a mix of HTML and PHP code.

    <!DOCTYPE html><html><body><h1>My PHP Website</h1><?php
    
      echo "Hello World!";
    ?></body></html>

    The “Hello World” message will be rendered as a plain text. However, you can put HTML tags inside the “Hello World” string. The browser will interpret the tags accordingly.

    In the following code, the “echo” statement renders “Hello World” so that it is in <h1> heading with the text aligned at the center of the page.

    <?php
       echo "<h1 align='center'>Hello World!</h1>";
    ?>

    PHP Script from Command Prompt

    You can run your PHP script from the command prompt. Let’s assume you have the following content in your “hello.php” file.

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

    Add the path of the PHP executable to your operating system’s path environment variable. For example, in a typical XAMPP installation on Windows, the PHP executable “php.exe” is present in “c:\xampp\php” directory. Add this directory in the PATH environment variable string.

    Now run this script as command prompt −

    C:\xampp\htdocs>php hello.php
    

    You will get the following output −

    Hello PHP!!!!!
    
  • Syntax

    The syntax rules of PHP are very similar to C Language. PHP is a server side scripting language. A PHP code is stored as a text file with “.php” extension. A “.php” file is essentially a web page with one or more blocks of PHP code interspersed in the HTML script. However, it must be opened in a browser with a HTTP protocol URL. In other words, if you double-click on the PHP file icon, it will be opened locally with the file protocol. For example, if you open the “index.php” file in the document root folder of your Apache server, it may just show the text of the PHP code. However, if you launch the Apache server and open the URL http://localhost/index.php, it displays the Apache home page.

    A “.php” file may contain HTML, CSS and JavaScript code blocks along with the PHP code. Hence, the PHP parser must differentiate between the PHP code from the other elements. When a “.php” file is opened in the web browser, the HTML engine renders the HTML/CSS/JavaScript part and escapes out of the HTML block as soon as the statements included in PHP tags are encountered. The PHP parser interpreter processes this block and returns the response to the browser.

    PHP Syntax

    PHP defines two methods of using tags for escaping the PHP code from HTML. Canonical PHP tags and Short-open (SGML-style) tags.

    Canonical PHP Tags

    The most universally effective PHP tag style is −

    <?php
       One or more PHP statements
    ?>

    If you use this style, you can be positive that your tags will always be correctly interpreted.

    Short-open (SGML-style) Tags

    Short or short-open tags look like this −

    <?php
    	One or more PHP statements
    ?>

    Short tags are, as one might expect, the shortest option. You must do one of two things to enable PHP to recognize the tags −

    • Choose the “–enable-short-tags” configuration option when you’re building PHP.
    • Set the “short_open_tag” setting in your php.ini file to on.
    short_open_tag=on
    

    This option must be disabled to parse XML with PHP because the same syntax is used for XML tags.

    The use of ASP-style tags −

    <%...%>

    and HTML script tags −

    <script language ="PHP">...</script>

    has been discontinued.

    Escaping from HTML

    The PHP parser ignores everything outside of a pair of opening and closing tags. Thus, a PHP file can have mixed content. This allows PHP to be embedded in HTML documents −

    <p>This is a HTML statement</p><?php echo This is a PHP statement.'; ?><p>This is another HTML statement.</p>

    A little advanced example of escaping using conditions is shown below −

    <?php if ($expression == true): ?>
       This HTML statement will be rendered.
    <?php else: ?>
       Otherwise this HTML statement will be rendered.
    <?php endif; ?>

    PHP skips the blocks where the condition is not met, even though they are outside of the PHP open/close tags.

    For outputting large blocks of text, dropping out of PHP parsing mode is generally more efficient than sending all of the text through echo or print.

    Basic Syntax of PHP

    The basic syntax of PHP is very similar to that of C and C++.

    Statements are expressions terminated by semicolons

    A statement in PHP is any expression that is followed by a semicolon (;). Any sequence of valid PHP statements that is enclosed by the PHP tags is a valid PHP program.

    Here is a typical statement in PHP, which in this case assigns a string of characters to a variable called “$greeting” −

    $greeting="Welcome to PHP!";

    A physical line in the text editor doesn’t have any significance in a PHP code. There may be multiple semicolon-terminated statements in a single line. On the other hand, a PHP statement may spill over more than one line if required.

    Expressions are combinations of tokens

    The smallest building blocks of PHP are the indivisible tokens such as numbers (3.14159), strings (“two”), variables ($two), constants (TRUE), and the special words that make up the syntax of PHP itself like “if”, “else”, “while”, “for”, and so forth.

    Braces make blocks

    Although statements cannot be combined like expressions, you can always put a sequence of statements anywhere a statement can go, by enclosing them in a set of curly braces.

    Here, both the following statements are equivalent −

    if(3==2+1)print("Good - I haven't totally lost my mind.");if(3==2+1){print("Good - I haven't totally");print("lost my mind.");}

    PHP is case sensitive

    PHP is a case sensitive language. The names of various PHP identifiers such as variable, function, class, etc., are case sensitive. As a result, the variable “$age” is not the same as “$Age”. Similarly, a function called “myfunction()” is different from another function called “MyFunction()”.

  • Features

    PHP (Hypertext Preprocessor) is an open-source server-side scripting language primarily used for web development. PHP can be embedded into HTML code.

    PHP is mainly used for server-side scripting, which runs scripts on the web server and then forwards the HTML they process to the web browser on the client. This makes it possible for programmers to design dynamic webpages that can manage sessions, handle forms, communicate with databases, and carry out a variety of other duties necessary for online applications.

    Features of PHP

    Over the years, PHP has incorporated numerous features. It is being consistently upgraded with new features and code revisions. In this chapter, let’s highlight some of the key features of PHP:

    PHP Features

    PHP is Simple and Easy to Learn

    The syntax of PHP compared to that of C, Java, and Perl, which makes it rather simple for developers to comprehend, particularly for those who are already familiar with other programming languages. Web apps can be developed quickly because of its generous pre-defined functions.

    PHP is Open Source

    PHP is free and open-source, meaning we can download it for free, and anyone can use it, modify it, and distribute. This encourages a sizable and vibrant developer community that uses forums, tutorials, and documentation to support and contribute to its development.

    PHP is Cross-Platform Compatible

    Numerous operating systems including Windows, Linux, macOS, and UNIX; and different databases like MongoDB, PostgreSQL, MySQL are compatible with PHP.

    PHP-based apps can operate on several environments without requiring any modifications due to this cross-platform inter-operability.

    Server-Side Scripting in PHP

    PHP is mainly used for server-side scripting, which runs scripts on the web server and then forwards the HTML they process to the web browser on the client. It helps the developers in Form Submission and Session Management with users across multiple requests.

    PHP Supports Easy Integration with Databases

    PHP offers strong database interaction support for various DBMS. It offers numerous built-in functions to achieve the database connection.

    PHP also includes database abstraction layer which integrates the communication between the application and the database. This makes it simple for developers to design database-driven web applications.

    PHP Provides Extensive Library Support

    PHP provides extensive libraries for various functionalities like image processing, encryption, PDF generation, parsing XML and JSON, handling sessions and cookies, and much more.

    Security Features in PHP

    PHP provides a plethora of built-in functions for data encryption. Developers can also leverage third-party applications for security.

    PHP employs security algorithms like Sha1 and MD5 to encrypt strings. Additionally, functions like filter_var and strip_tags contribute in maintaining a secure environment for the users. PHP also supports secure communication protocols like HTTPS.

    Efficient Memory and Session Management in PHP

    PHP is a reliable language due to its efficient memory management and session management. It avoids unnecessary memory allocation.

    PHP code runs in its own memory space which makes it faster compared to other scripting languages making it more efficient. In PHP, the database connections are also fast.

    PHP Has Active Community and Support

    Since PHP is an open-source platform, it has a vibrant community of developers who actively contribute to its development, share knowledge, provide support, and create third-party tools and frameworks.

    Due to this active community support, PHP remains up-to-date and developers can easily seek help from other community members in case they get any errors or exceptions while writing PHP codes.

  • History

    PHP started out as a small open-source project that evolved gradually as more and more people found out how useful it was. Rasmus Lerdorf released the first version of PHP way back in 1994. At that time, PHP stood for Personal Home Page, as he used it to maintain his personal homepage. Later on, he added database support and called it as “Personal Home Page/Forms Interpreter” or PHP/FI, which could be used to build simple, dynamic web applications.

    • Zeev Suraski and Andi Gutmans rewrote the parser in 1997 and formed the base of PHP 3. The name of the language was also changed to the recursive acronym PHP: Hypertext Preprocessor. They are also the authors of Zend Engine, a compiler and runtime environment for the PHP. Zend Engine powered PHP 4 was released in May 2000.
    • PHP 5 was released in 2004, which included many new features such as OOP support, the PHP Data Objects (PDO), and numerous performance enhancements.
    • PHP 7, is a new major PHP version which was developed in 2015. It included new language features, most notable being, the introduction of return type declarations for functions which complement the existing parameter type declarations, and support for the scalar types (integer, float, string, and boolean) in parameter and return type declarations.

    New Features in PHP 8

    PHP 8 is the latest major version, released in November 2020. Some of the new features and notable changes include:

    Just-in-time (JIT) Compilation

    PHP 8’s JIT compiler provides substantial performance improvements mathematical-type operations than for common web-development use cases. The JIT compiler provides the future potential to move some code from C to PHP.

    The “match: Expression

    The newly introduced “match” expression is more compact than a switch statement. Because match is an expression, its result can be assigned to a variable or returned from a function.

    PHP 8 – Type Changes and Additions

    PHP 8 introduced union types, a new static return type, and a new mixed type. PHP 8 also provided Attributes, (similar to “annotations” in other programming languages) that help in adding metadata to PHP classes.

    In addition, there have been many changes and additions to the PHP standard library. PHP 8.2.9 is the latest stable version available.

    Important milestones in PHP’s release history are summarized in the following table −

    VersionDescription
    Version 1.0
    (8 June 1995)
    Officially called “Personal Home Page Tools (PHP Tools)”. This is the first use of the name “PHP”.
    Version 2.0
    (1 November 1997)
    Officially called “PHP/FI 2.0”. This is the first release that could actually be characterised as PHP, being a standalone language with many features that have endured to the present day.
    Version 3.0
    (6 June 1998)
    Development moves from one person to multiple developers.Zeev Suraski and Andi Gutmans rewritten the base for this version.
    Version 4.0
    (22 May 2000)
    Added more advanced two-stage parse/execute tag-parsing system called the Zend engine.
    Version 5.0
    (13 July 2004)
    Zend Engine II with a new object model.
    Version 5.1
    (24 November 2005)
    Performance improvements with the introduction of compiler variables in re-engineered PHP Engine.Added PHP Data Objects (PDO) as a consistent interface for accessing databases.
    Version 6.x
    Not released
    Abandoned version of PHP that planned to include native Unicode support.
    Version 7.0
    (3 December 2015)
    Zend Engine 3 ,Uniform variable syntax,Added Closure:call(),?? (null coalesce) operator,Return type declarations,Scalar type declarations,<=> “spaceship” three-way comparison operator,Anonymous classes
    Version 7.3
    (6 December 2018)
    Flexible Heredoc and Nowdoc syntax
    Version 8.0
    (26 November 2020)
    Just-In-Time (JIT) compilation,Arrays starting with a negative index,TypeError on invalid arithmetic/bitwise operators,Variable syntax tweaks,Attributes,Named arguments,Match expression,Union types, Mixed type,Static return type
  • Installation

    You can start learning the basics of programming in PHP with the help of any of the online PHP compilers freely available on the Internet. This will help in getting acquainted with the features of PHP without installing it on your computer. Later on, install a full-fledged PHP environment on your local machine.

    One such online PHP compiler is provided by Tutorialpoint’s “Coding Ground for Developers”. Visit https://www.tutorialspoint.com/codingground.htm, enter PHP script and execute it.

    PHP Installation

    However, to be able to learn the advanced features of PHP, particularly related to the web concepts such as server variables, using backend databases, etc., you need to install the PHP environment on your local machine.

    In order to develop and run PHP Web pages, you neeed to install three vital components on your computer system.

    • Web Server − PHP will work with virtually all Web Server software, including Microsoft’s Internet Information Server (IIS), NGNIX, or Lighttpd etc. The most often used web server software is the freely available Apache Server. Download Apache for free here − https://httpd.apache.org/download.cgi
    • Database − PHP will work with virtually all database software, including Oracle and Sybase but most commonly used is freely available MySQL database. Download MySQL for free here − https://www.mysql.com/downloads/
    • PHP Parser − In order to process PHP script instructions a parser must be installed to generate HTML output that can be sent to the Web Browser.

    Although it is possible to install these three components separately, and configure the installation correctly, it is a little complex process, particularly for the beginners. Instead, using any all-in-one packaged distribution that contains precompiled Apache, MySQL and PHP binaries is convenient.

    XAMPP Installation

    There are many precompiled bundles available both in open-source as well as proprietary distributions. XAMPP, from Apache Friends (https://www.apachefriends.org/) is one of the most popular PHP enabled web server packages. We shall be using XAMPP in this tutorial.

    XAMPP is an easy to install Apache distribution that contains Apache, MariaDB, PHP and Perl. The letter X in the acronym indicates that it is a cross-platform software, available for use on Windows, Linux and OS X. Note that XAMPP includes MariaDB, which is a fork of MySQL, with no difference in its functionality.

    To download the respective installer for your operating system, visit https://www.apachefriends.org/download.html, and download one of the following −

    • Windows − https://sourceforge.net/projects/
    • Linux − https://sourceforge.net/projects/
    • OS X − https://sourceforge.net/projects/

    Using the installer on Windows is a completely wizard based installation. All you need to provide is an administrator access and the location of the installation directory which is “c:\xampp” by default.

    To install XAMPP on Linux, use the following steps −

    Step 1 − Change the permissions to the installer −

    chmod 755 xampp-linux-*-installer.run
    

    Run the installer −

    sudo ./xampp-linux-*-installer.run
    

    XAMPP is now installed below the “/opt/lamp” directory.

    Step 2 − To start XAMPP simply call this command −

    sudo /opt/lampp/lampp start
    

    You should now see something like this on your screen −

    Starting XAMPP...LAMPP: Starting Apache...LAMPP: Starting MySQL...LAMPP started.
    Ready. Apache and MySQL are running.

    You can also use a graphical tool to manage your servers easily. You can start this tool with the following commands −

    cd /opt/lampp
    sudo ./manager-linux.run(or manager-linux-x64.run)

    Step 3 − To stop XAMPP simply call this command −

    sudo /opt/lampp/lampp stop
    

    You should now see something like this on your screen −

    Stopping XAMPP...LAMPP: Stopping Apache...LAMPP: Stopping MySQL...LAMPP stopped.

    Also, note that there is a graphical tool that you can use to start/stop your servers easily. You can start this tool with the following commands −

    cd /opt/lampp
    sudo ./manager-linux.run(or manager-linux-x64.run)

    If you are using OS X, follow these steps −

    • To start the installation, Open the DMG-Image, and double-click the image to start the installation process.
    • To start XAMPP simply open XAMPP Control and start Apache, MySQL and ProFTPD. The name of the XAMPP Control is “manager-osx”.
    • To stop XAMPP simply open XAMPP Control and stop the servers. The name of the XAMPP Control is “manager-osx”.
    • The XAMPP control panel is a GUI tool from which the Apache server, and MySQL can be easily started and stopped.
    PHP Installation 2

    Press the Admin button after starting the Apache module. The XAMPP homepage appears like the one shown below −

    PHP Installation 3

    PHP Parser Installation

    Before you proceed it is important to make sure that you have proper environment setup on your machine to develop your web programs using PHP.

    Type the following address into your browser’s address box.

    http://127.0.0.1/info.php
    

    If this displays a page showing your PHP installation related information then it means you have PHP and Webserver installed properly. Otherwise you have to follow given procedure to install PHP on your computer.

    This section will guide you to install and configure PHP over the following four platforms −

    • PHP Installation on Linux or Unix with Apache
    • PHP Installation on Mac OS X with Apache
    • PHP Installation on Windows NT/2000/XP with IIS
    • PHP Installation on Windows NT/2000/XP with Apache

    Apache Configuration

    If you are using Apache as a Web Server then this section will guide you to edit Apache Configuration Files.

    Just Check it here − PHP Configuration in Apache Server

    PHP.INI File Configuration

    The PHP configuration file, php.ini, is the final and most immediate way to affect PHP’s functionality.

    Just Check it here − PHP.INI File Configuration

    Windows IIS Configuration

    To configure IIS on your Windows machine you can refer your IIS Reference Manual shipped along with IIS.

    You now have a complete PHP development environment on your local machine.

  • Introduction

    PHP started out as a small open source project that evolved as more and more people found out how useful it was. Rasmus Lerdorf released the first version of PHP way back in 1994. Initially, PHP was supposed to be an abbreviation for “Personal Home Page”, but it now stands for the recursive initialism “PHP: Hypertext Preprocessor”.

    Lerdorf began PHP development in 1993 by writing several Common Gateway Interface (CGI) programs in C, which he used to maintain in his personal homepage. Later on, He extended them to work with web forms and to communicate with databases. This implementation of PHP was “Personal Home Page/Forms Interpreter” or PHP/FI.

    Today, PHP is the world’s most popular server-side programming language for building web applications. Over the years, it has gone through successive revisions and versions.

    PHP Versions

    PHP was developed by Rasmus Lerdorf in 1994 as a simple set of CGI binaries written in C. He called this suite of scripts “Personal Home Page Tools”. It can be regarded as PHP version 1.0.

    • In April 1996, Rasmus introduced PHP/FI. Included built-in support for DBM, mSQL, and Postgres95 databases, cookies, user-defined function support. PHP/FI was given the version 2.0 status.
    • PHP: Hypertext Preprocessor – PHP 3.0 version came about when Zeev Suraski and Andi Gutmans rewrote the PHP parser and acquired the present-day acronym. It provided a mature interface for multiple databases, protocols and APIs, object-oriented programming support, and consistent language syntax.
    • PHP 4.0 was released in May 2000 powered by Zend Engine. It had support for many web servers, HTTP sessions, output buffering, secure ways of handling user input and several new language constructs.
    • PHP 5.0 was released in July 2004. It is mainly driven by its core, the Zend Engine 2.0 with a new object model and dozens of other new features. PHP’s development team includes dozens of developers and others working on PHP-related and supporting projects such as PEAR, PECL, and documentation.
    • PHP 7.0 was released in Dec 2015. This was originally dubbed PHP next generation (phpng). Developers reworked Zend Engine is called Zend Engine 3. Some of the important features of PHP 7 include its improved performance, reduced memory usage, Return and Scalar Type Declarations and Anonymous Classes.
    • PHP 8.0 was released on 26 November 2020. This is a major version having many significant improvements from its previous versions. One standout feature is Just-in-time compilation (JIT) that can provide substantial performance improvements. The latest version of PHP is 8.2.8, released on July 4th, 2023.

    PHP Application Areas

    PHP is one of the most widely used language over the web. Here are some of the application areas of PHP −

    • PHP is a server-side scripting language that is embedded in HTML. It is used to manage dynamic content, databases, session tracking, even build entire e-commerce sites. Although it is especially suited to web development, you can also build desktop standalone applications as PHP also has a command-line interface. You can use PHP-GTK extension to build GUI applications in PHP.
    • PHP is widely used for building web applications, but you are not limited to output only HTML. PHP’s ouput abilities include rich file types, such as images or PDF files, encrypting data, and sending emails. You can also output easily any text, such as JSON or XML.
    • PHP is a cross-platform language, capable of running on all major operating system platforms and with most of the web server programs such as Apache, IIS, lighttpd and nginx. PHP also supports other services using protocols such as LDAP, IMAP, SNMP, NNTP, POP3, HTTP, COM, etc.

    Here are some more important features of PHP −

    • PHP performs system functions. It can create, open, read, write, and close the files.
    • PHP can handle forms. It can gather data from files, save data to a file, through email you can send data, return data to the user.
    • You add, delete, modify elements within your database through PHP.
    • Access cookies variables and set cookies.
    • Using PHP, you can restrict users to access some pages of your website.
    • It can encrypt data.

    PHP provides a large number of reusable classes and libraries are available on “PEAR” and “Composer”. PEAR (PHP Extension and Application Repository) is a distribution system for reusable PHP libraries or classes. “Composer” is a dependency management tool in PHP.

  • Data Output

    Data export (or output) in MATLAB means to write into files. MATLAB allows you to use your data in another application that reads ASCII files. For this, MATLAB provides several data export options.

    You can create the following type of files −

    • Rectangular, delimited ASCII data file from an array.
    • Diary (or log) file of keystrokes and the resulting text output.
    • Specialized ASCII file using low-level functions such as fprintf.
    • MEX-file to access your C/C++ or Fortran routine that writes to a particular text file format.

    Apart from this, you can also export data to spreadsheets.

    There are two ways to export a numeric array as a delimited ASCII data file −

    • Using the save function and specifying the -ascii qualifier
    • Using the dlmwrite function

    Syntax for using the save function is −

    save my_data.out num_array -ascii
    

    where, my_data.out is the delimited ASCII data file created, num_array is a numeric array and −ascii is the specifier.

    Syntax for using the dlmwrite function is −

    dlmwrite('my_data.out', num_array, 'dlm_char')
    

    where, my_data.out is the delimited ASCII data file created, num_array is a numeric array and dlm_char is the delimiter character.

    Example

    The following example demonstrates the concept. Create a script file and type the following code −

    num_array = [ 1 2 3 4 ; 4 5 6 7; 7 8 9 0];
    save array_data1.out num_array -ascii;
    type array_data1.out
    dlmwrite('array_data2.out', num_array, ' ');
    type array_data2.out

    When you run the file, it displays the following result −

       1.0000000e+00   2.0000000e+00   3.0000000e+00   4.0000000e+00
       4.0000000e+00   5.0000000e+00   6.0000000e+00   7.0000000e+00
       7.0000000e+00   8.0000000e+00   9.0000000e+00   0.0000000e+00
    
    1 2 3 4
    4 5 6 7
    7 8 9 0
    

    Please note that the save -ascii command and the dlmwrite function does not work with cell arrays as input. To create a delimited ASCII file from the contents of a cell array, you can

    • Either, convert the cell array to a matrix using the cell2mat function
    • Or export the cell array using low-level file I/O functions.

    If you use the save function to write a character array to an ASCII file, it writes the ASCII equivalent of the characters to the file.

    For example, let us write the word ‘hello’ to a file −

    h = 'hello';
    save textdata.out h -ascii
    type textdata.out

    MATLAB executes the above statements and displays the following result. which is the characters of the string ‘hello’ in 8-digit ASCII format.

    1.0400000e+02   1.0100000e+02   1.0800000e+02   1.0800000e+02   1.1100000e+02
    

    Writing to Diary Files

    Diary files are activity logs of your MATLAB session. The diary function creates an exact copy of your session in a disk file, excluding graphics.

    To turn on the diary function, type −

    diary

    Optionally, you can give the name of the log file, say −

    diary logdata.out
    

    To turn off the diary function −

    diary off
    

    You can open the diary file in a text editor.

    Exporting Data to Text Data Files with Low-Level I/O

    So far, we have exported numeric arrays. However, you may need to create other text files, including combinations of numeric and character data, nonrectangular output files, or files with non-ASCII encoding schemes. For these purposes, MATLAB provides the low-level fprintf function.

    As in low-level I/O file activities, before exporting, you need to open or create a file with the fopen function and get the file identifier. By default, fopen opens a file for read-only access. You should specify the permission to write or append, such as ‘w’ or ‘a’.

    After processing the file, you need to close it with fclose(fid) function.

    The following example demonstrates the concept −

    Example

    Create a script file and type the following code in it −

    % create a matrix y, with two rows
    x = 0:10:100;
    y = [x; log(x)];
     
    % open a file for writing
    fid = fopen('logtable.txt', 'w');
     
    % Table Header
    fprintf(fid, 'Log     Function\n\n');
     
    % print values in column order
    % two values appear on each row of the file
    fprintf(fid, '%f    %f\n', y);
    fclose(fid);
    
    % display the file created
    type logtable.txt

    When you run the file, it displays the following result −

    Log         Function
    
    0.000000    -Inf
    10.000000    2.302585
    20.000000    2.995732
    30.000000    3.401197
    40.000000    3.688879
    50.000000    3.912023
    60.000000    4.094345
    70.000000    4.248495
    80.000000    4.382027
    90.000000    4.499810
    100.000000    4.605170
    
  • Data Import

    Importing data in MATLAB means loading data from an external file. The importdata function allows loading various data files of different formats. It has the following five forms −

    Sr.No.Function & Description
    1A = importdata(filename)Loads data into array A from the file denoted by filename.
    2A = importdata(‘-pastespecial’)Loads data from the system clipboard rather than from a file.
    3A = importdata(___, delimiterIn)Interprets delimiterIn as the column separator in ASCII file, filename, or the clipboard data. You can use delimiterIn with any of the input arguments in the above syntaxes.
    4A = importdata(___, delimiterIn, headerlinesIn)Loads data from ASCII file, filename, or the clipboard, reading numeric data starting from line headerlinesIn+1.
    5[A, delimiterOut, headerlinesOut] = importdata(___)Returns the detected delimiter character for the input ASCII file in delimiterOut and the detected number of header lines in headerlinesOut, using any of the input arguments in the previous syntaxes.

    By default, Octave does not have support for importdata() function, so you will have to search and install this package to make following examples work with your Octave installation.

    Example 1

    Let us load and display an image file. Create a script file and type the following code in it −

    filename = 'smile.jpg';
    A = importdata(filename);
    image(A);

    When you run the file, MATLAB displays the image file. However, you must store it in the current directory.

    Importing Imange Files

    Example 2

    In this example, we import a text file and specify Delimiter and Column Header. Let us create a space-delimited ASCII file with column headers, named weeklydata.txt.

    Our text file weeklydata.txt looks like this −

    SunDay  MonDay  TuesDay  WednesDay  ThursDay  FriDay  SaturDay
    95.01   76.21   61.54    40.57       55.79    70.28   81.53
    73.11   45.65   79.19    93.55       75.29    69.87   74.68
    60.68   41.85   92.18    91.69       81.32    90.38   74.51
    48.60   82.14   73.82    41.03       0.99     67.22   93.18
    89.13   44.47   57.63    89.36       13.89    19.88   46.60
    

    Create a script file and type the following code in it −

    filename = 'weeklydata.txt';
    delimiterIn = ' ';
    headerlinesIn = 1;
    A = importdata(filename,delimiterIn,headerlinesIn);
    
    % View data
    for k = [1:7]
       disp(A.colheaders{1, k})
       disp(A.data(:, k))
       disp(' ')
    end

    When you run the file, it displays the following result −

    SunDay
       95.0100
       73.1100
       60.6800
       48.6000
       89.1300
     
    MonDay
       76.2100
       45.6500
       41.8500
       82.1400
       44.4700
     
    TuesDay
       61.5400
       79.1900
       92.1800
       73.8200
       57.6300
    
    WednesDay
       40.5700
       93.5500
       91.6900
       41.0300
       89.3600
     
    ThursDay
       55.7900
       75.2900
       81.3200
       0.9900
       13.8900
     
    FriDay
       70.2800
       69.8700
       90.3800
       67.2200
       19.8800
    
    SaturDay
       81.5300
       74.6800
       74.5100
       93.1800
       46.6000
    

    Example 3

    In this example, let us import data from clipboard.

    Copy the following lines to the clipboard −

    Mathematics is simple

    Create a script file and type the following code −

    A = importdata('-pastespecial')
    

    When you run the file, it displays the following result −

    A = 
       'Mathematics is simple'
    

    Low-Level File I/O

    The importdata function is a high-level function. The low-level file I/O functions in MATLAB allow the most control over reading or writing data to a file. However, these functions need more detailed information about your file to work efficiently.

    MATLAB provides the following functions for read and write operations at the byte or character level −

    FunctionDescription
    fcloseClose one or all open files
    feofTest for end-of-file
    ferrorInformation about file I/O errors
    fgetlRead line from file, removing newline characters
    fgetsRead line from file, keeping newline characters
    fopenOpen file, or obtain information about open files
    fprintfWrite data to text file
    freadRead data from binary file
    frewindMove file position indicator to beginning of open file
    fscanfRead data from text file
    fseekMove to specified position in file
    ftellPosition in open file
    fwriteWrite data to binary file

    Import Text Data Files with Low-Level I/O

    MATLAB provides the following functions for low-level import of text data files −

    • The fscanf function reads formatted data in a text or ASCII file.
    • The fgetl and fgets functions read one line of a file at a time, where a newline character separates each line.
    • The fread function reads a stream of data at the byte or bit level.

    Example

    We have a text data file ‘myfile.txt’ saved in our working directory. The file stores rainfall data for three months; June, July and August for the year 2012.

    The data in myfile.txt contains repeated sets of time, month and rainfall measurements at five places. The header data stores the number of months M; so we have M sets of measurements.

    The file looks like this −

    Rainfall Data
    Months: June, July, August
     
    M = 3
    12:00:00
    June-2012
    17.21  28.52  39.78  16.55 23.67
    19.15  0.35   17.57  NaN   12.01
    17.92  28.49  17.40  17.06 11.09
    9.59   9.33   NaN    0.31  0.23 
    10.46  13.17  NaN    14.89 19.33
    20.97  19.50  17.65  14.45 14.00
    18.23  10.34  17.95  16.46 19.34
    09:10:02
    July-2012
    12.76  16.94  14.38  11.86 16.89
    20.46  23.17  NaN    24.89 19.33
    30.97  49.50  47.65  24.45 34.00
    18.23  30.34  27.95  16.46 19.34
    30.46  33.17  NaN    34.89  29.33
    30.97  49.50  47.65  24.45 34.00
    28.67  30.34  27.95  36.46 29.34
    15:03:40
    August-2012
    17.09  16.55  19.59  17.25 19.22
    17.54  11.45  13.48  22.55 24.01
    NaN    21.19  25.85  25.05 27.21
    26.79  24.98  12.23  16.99 18.67
    17.54  11.45  13.48  22.55 24.01
    NaN    21.19  25.85  25.05 27.21
    26.79  24.98  12.23  16.99 18.67
    

    We will import data from this file and display this data. Take the following steps −

    • Open the file with fopen function and get the file identifier.
    • Describe the data in the file with format specifiers, such as ‘%s‘ for a string, ‘%d‘ for an integer, or ‘%f‘ for a floating-point number.
    • To skip literal characters in the file, include them in the format description. To skip a data field, use an asterisk (‘*’) in the specifier.For example, to read the headers and return the single value for M, we write −M = fscanf(fid, ‘%*s %*s\n%*s %*s %*s %*s\nM=%d\n\n’, 1);
    • By default, fscanf reads data according to our format description until it does not find any match for the data, or it reaches the end of the file. Here we will use for loop for reading 3 sets of data and each time, it will read 7 rows and 5 columns.
    • We will create a structure named mydata in the workspace to store data read from the file. This structure has three fields – timemonth, and raindata array.

    Create a script file and type the following code in it −

    filename = '/data/myfile.txt';
    rows = 7;
    cols = 5;
     
    % open the file
    fid = fopen(filename);
     
    % read the file headers, find M (number of months)
    M = fscanf(fid, '%*s %*s\n%*s %*s %*s %*s\nM=%d\n\n', 1);
     
    % read each set of measurements
    for n = 1:M
       mydata(n).time = fscanf(fid, '%s', 1);
       mydata(n).month = fscanf(fid, '%s', 1);
     
       % fscanf fills the array in column order,
       % so transpose the results
       mydata(n).raindata  = ...
    
      fscanf(fid, '%f', &#91;rows, cols]);
    end for n = 1:M disp(mydata(n).time), disp(mydata(n).month) disp(mydata(n).raindata) end % close the file fclose(fid);

    When you run the file, it displays the following result −

    12:00:00
    June-2012
       17.2100   17.5700   11.0900   13.1700   14.4500
       28.5200       NaN    9.5900       NaN   14.0000
       39.7800   12.0100    9.3300   14.8900   18.2300
       16.5500   17.9200       NaN   19.3300   10.3400
       23.6700   28.4900    0.3100   20.9700   17.9500
       19.1500   17.4000    0.2300   19.5000   16.4600
       0.3500   17.0600   10.4600   17.6500   19.3400
    
    09:10:02
    July-2012
       12.7600       NaN   34.0000   33.1700   24.4500
       16.9400   24.8900   18.2300       NaN   34.0000
       14.3800   19.3300   30.3400   34.8900   28.6700
       11.8600   30.9700   27.9500   29.3300   30.3400
       16.8900   49.5000   16.4600   30.9700   27.9500
       20.4600   47.6500   19.3400   49.5000   36.4600
       23.1700   24.4500   30.4600   47.6500   29.3400
    
    15:03:40
    August-2012
       17.0900   13.4800   27.2100   11.4500   25.0500
       16.5500   22.5500   26.7900   13.4800   27.2100
       19.5900   24.0100   24.9800   22.5500   26.7900
       17.2500       NaN   12.2300   24.0100   24.9800
       19.2200   21.1900   16.9900       NaN   12.2300
       17.5400   25.8500   18.6700   21.1900   16.9900
       11.4500   25.0500   17.5400   25.8500   18.6700