- PHP: Basic Syntax

PHP: Basic Syntax


As PHP was originally developed as a programmable layer on top of HTML, PHP script can be placed anywhere within an existing HTML document and launched upon loading the page, as long as the following requirements are satisfied:

  • File extension is switched to .php
  • File is hosted by a server (local or remote) that can handle PHP files

Simply inserting PHP code and loading the page on the macOS browser (ex. Safari) will not work, and this is why the server is provided as part of this course. One may, however, opt to turn a personal computer into a web server.

Get Started

Consider the following PHP page (a simple HTML file with PHP extension):



        $color = "red";
        echo $color;



<?php (can be shortened to <?) and ?> identify where PHP code starts and ends. All PHP scripts written between the two tags are identified, analyzed, and compiled by the web server, and its output is pushed to the web browser.

In the the above example, the programmer creates a variable (container of information) in the PHP world, and sets its value to "red". This value remains only in the backend and inaccessible to the browser, until the programmer decides to "print" the value, bringing it to the front-end level.


Each variable can be defined with a $ sign, followed by the desired name:



        $hello = "Welcome";
        $x = 10;
        $y = 5;
        $z = $x * $y;



As illustrated above, one can define multiple variables of different data types, and even concatenate texts or perform simple arithmetics by referring to multiple variables. The above example illustrates how one can calculate a product (multiplication) of two variables. Finally, note that all this backend code will continue to stay away from the front-end until one decides to "print" the variable.

Data Types

Variables can come in different forms and sizes. Including the above examples, PHP features the following data types with specific use cases:

  • String: Text content
    • "helloworld"
  • Integer: Non-decimal number
    • 13
  • Float: Decimal number
    • 0.125
  • Boolean: Binary state
    • false
  • Array: Flat list of entries
    • array("BMW", "Audi", "Kia")
  • Object: Structre best suited for complex properties
    • $person->first_name
  • Null: Variable without any value
    • NULL

More To Come

There are other fundamental programming concepts yet to be explored here, and they will be discussed as the need arises in subsequent chapters.