Thursday, May 7, 2020

Data-types, Variables and Operators

PHP Data types

A variable can store different types of Data. Let’s have a look at some of the data types supported by PHP:


PHP String

A string is a sequence of characters. In PHP, you can write the string inside single or double quotes.

<?php $a = "Hello World!";
$b = 'Hello World!';
echo $a;
echo "<br>";
echo $b
?>

PHP Integer

An integer data type is a non-decimal number between -2,147,483,648 and 2,147,483,647. An integer must have at least one digit and can be either positive or negative.
The following example takes $a as an integer. The PHP var_dump() function returns the data type and value.

<?php 
$a = 0711;
var_dump($a); 
?> 

PHP Float

A float or floating point number is a number with a decimal point or a number in exponential form.

The following example takes $a as a float and the PHP var_dump() function returns the data type and value.

<?php
$a = 14.763;
var_dump($a);
?> 

PHP Boolean

A Boolean represents two possible states: TRUE or FALSE. They are often used in conditional testing.

$a = true;
$b = false;

PHP Object

An object is a data type which stores data and information on how to process that data. In PHP, an object must be explicitly declared. We need to declare a class of object using the class keyword.

<?php
class Student
{
    function Student()
    {
    $this->name = “XYZ”;
    }
}
// create an object
$Daniel = new Student(); // show object properties
echo $Daniel->name
?>

PHP Array

An array stores multiple values in one single variable. In the following example, the PHP var_dump() function returns the data type and value.

<?php 
$students = array(“Daniel”,”Josh”,”Sam”);
var_dump($students); 
?>

Now that you have learnt about the various Data Types, let’s move ahead with the PHP Tutorial and have a look at the different PHP Variables. 

PHP Variables

Variables are containers for storing information. All variables in PHP are denoted with a leading dollar sign ($). Unlike other programming languages, PHP has no command for declaring a variable. It is created the moment you first assign a value to it.

Declaring PHP Variables:

<?php
$txt = "Hello World!";
$a = 7;
$b = 11.5
?>

The PHP echo statement is often used to output data to the screen.

PHP Variables Scope

In PHP, variables can be declared anywhere in the script. The scope of a variable is the part of the script where the variable can be used.

In PHP we have three different variable scopes:

            1. Local – A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function:

<?php 
    function myTest() 
    { 
    $a = 7// local scope 
    echo "<p>Variable a inside function is: $a</p>"
    } 
    myTest(); // using x outside the function will generate an error echo 

"<p>Variable a outside function is: $a</p>"
?>

2. Global– A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function. The global keyword is used to access a global variable from within a function:

<?php
$a = 9// global scope
function myTest() {
// using a inside this function will generate an error
echo "<p>Variable a inside function is: $a</p>";
}
myTest();
echo "<p>Variable a outside function is: $a</p>"
?>
  1. Static– When a function is executed, all of its variables are deleted. But if you want any variable not to be deleted, the static keyword is used when you first declare the variable:
<?php
function myTest() 
{
static $a = 0;
echo $a$a++; 
}
myTest();
myTest();
myTest();
?>

Now that you know about the declaration of variables, let’s move ahead with the PHP Tutorial and have a look at the operators in PHP.

PHP Operators

Operators are used for performing different operations on variables. Let’s have a look at the different operators in PHP:

  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Logical operators
  • Array operators

Arithmetic Operators

The PHP arithmetic operators are used with numeric values to perform common arithmetical operations, such as addition, subtraction, multiplication etc.

Operator

Name

Example

Result

+

Addition

$a + $b

Sum of $a and $b

Subtraction

$a – $b

Difference of $a and $b

*

Multiplication

$a * $b

Product of $a and $b

/

Division

$a / $b

Quotient of $a and $b

%

Modulus

$a % $b

Remainder of $a divided by $b

**

Exponentiation

$a ** $b

Result of raising $a to the $b’th power

 

Assignment Operators

The PHP assignment operators are used with numeric values to write a value to a variable.

Assignment

Similar to

Result

a = b

a = b

The left operand gets set to the value of the expression on the right.

a += b

a = a + b

Addition

a -= b

a = a – b

Subtraction

 

Comparison Operators

The PHP comparison operators are used to compare two numbers or strings

Operator

Name

Example

==

Equal

$a == $b

===

Identical

$a === $b

!=

Not equal

$a != $b

<> 

Not equal

$a <> $b

!==

Not identical

$a !== $b

> 

Greater than

$a > $b

< 

Less than

$a < $b

>=

Greater than or equal to

$a >= $b

<=

Less than or equal to

$a <= $b

 

Logical Operators

The PHP logical operators are used to combine conditional statements.

Operator

Name

Example

and

And

True if both $a & $b are true

or

Or

True if either $a or $b are true

xor

Xor

True if either $a or $b are true, but not both

&&

And

True if both $a & $b are true

||

Or

True if either $a or $b are true

!

Not

True if $a is not true

 

Array Operators

The PHP array operators are used to compare arrays.

Operator 

Name

Example

+

Union

$a + $b

==

Equality

$a == $b

===

Identity

$a === $b

!=

Inequality

$a != $b

<> 

Inequality

$a <> $b

!==

Non-identity

$a !== $b

 Now let’s move ahead with our PHP Tutorial and have a look at the various OOP concepts in PHP.



Embedding PHP in HTML

PHP is an HTML-embedded server-side scripting language. When building a complex page, at some point you will be faced with the need to combine PHP and HTML to achieve your needed results. At the first point, this can seem complicated, since PHP and HTML are two separate languages, but this is not the case. PHP is designed to interact with HTML and PHP scripts can be included in an HTML page without a problem.

In an HTML page, PHP code is enclosed within special PHP tags. When a visitor opens the page, the server processes the PHP code and then sends the output (not the PHP code itself) to the visitor's browser. Actually, it is quite simple to integrate HTML and PHP. A PHP script can be treated as an HTML page, with bits of PHP inserted here and there. Anything in a PHP script that is not contained within <?php ?> tags is ignored by the PHP compiler and passed directly to the web browser. If you look at the example below you can see what a full PHP script might look like:

Recommended usage:

<html>
<head>
</head>
<body class="page_bg">
Hello, today is <?php echo date('l, F jS, Y'); ?>.
</body>
</html>


The code above is simply HTML, with just a bit of PHP that prints out today's date using the built-in date function. As mentioned above, all of the plain HTML in the code above will be ignored by the PHP compiler and passed through to the web browser untouched.

 More advanced techniques:

<html>
<head></head>
<body>
<ul>
<?php for($i=1;$i<=5;$i++){ ?>
<li>Menu Item <?php echo $i?></li>
<?php } ?>
</ul>
</body>
</html>

and the result is:

· Menu Item 1
· Menu Item 2
· Menu Item 3
· Menu Item 4
· Menu Item 5

 

PHP in HTML using short_open_tag

If you want to shorten your code as much as possible, you can go for the short_tags option. This will save you from typing <?php at the beginning of the code, shortening it to just <?.

PHP in HTML using short_tags:

<html>
<head></head>
<body class="page_bg">
Hello, today is <?=date('l, F jS, Y'); ?>.
</body>
</html>

Have in mind that if you want to build a website compatible with as many platforms as possible, you should not rely on short_tags.

HTML in PHP using echo

A possible way to integrate HTML tags in a PHP file is via the echo command:

Possible yet not recommended usage:

<?php
echo "<html>";
echo "<head></head>";
echo "<body class=\"page_bg\">";
echo "Hello, today is ";
echo date('l, F jS, Y'); //other php code here echo "</body>";
echo "</html>";
?>

This will, however, affect the HTML Code Coloring option in most HTML/PHP editors, which allows for an easy understanding of the role of HTML tags. You should escape each double quote within the HTML code with a backslash.


Comments in PHP

The word comment itself expresses its meaning as commenting out something. If we comment on anything in the PHP program file, it will not be compiled with the code. The compiler or the interpreter will simply ignore this.

There are two types of comments you can add:

1.     Single line comment used for quick notes about complex code or to temporarily disable a line of PHP code. You need to add // or # before the code.

Example-1 :

<?php
echo "This is my first PHP Program";
// this is the first program
?>

 

Example-2 :

<?php
# $i=10;
# $j=20;
# echo $i + $j;
echo "Hello World!";
# this is PHP comment
?>

 

2.     Multi-line comment used to comment out large blocks of code or writing multiple line comments. You need to add /* before and */ after the code.

Example:

<?php
    /* The following line of code
       will output the "Hello World!" message */
    echo "Hello World!";
?>

Introduction to PHP

PHP is a server-side scripting language. That is used to develop Static websites or Dynamic websites or Web applications. PHP stands for Hypertext Pre-processor, that earlier stood for Personal Home Pages.

  • PHP scripts can only be interpreted on a server that has PHP installed.
  • The client computers accessing the PHP scripts require a web browser only.
  • A PHP file contains PHP tags and ends with the extension ".php".

What is Scripting Language?

  • A script is a set of programming instructions that is interpreted at runtime.
  • A scripting language is a language that interprets scripts at runtime. Scripts are usually embedded into other software environments.
  • The purpose of the scripts is usually to enhance the performance or perform routine tasks for an application.
  • Server-side scripts are interpreted on the server while client side scripts are interpreted by the client application.
  • PHP is a server-side script that is interpreted on the server while JavaScript is an example of a client-side script that is interpreted by the client browser. Both PHP and JavaScript can be embedded into HTML pages.

Programming Language Vs Scripting Language

Programming language

Scripting language

Has all the features needed to develop complete applications.

Mostly used for routine tasks

The code has to be compiled before it can be executed

The code is usually executed without compiling

Does not need to be embedded into other languages

Is usually embedded into other software environments.

What does PHP stand for?

PHP means - Personal Home Page, but it now stands for the recursive backronym PHP: Hypertext Preprocessor.

PHP code may be embedded into HTML code, or it can be used in combination with various web template systems, web content management system and web frameworks.

Php Syntax

A PHP file can also contain tags such as HTML and client side scripts such as JavaScript.

  • HTML is an added advantage when learning PHP Language. You can even learn PHP without knowing HTML but it’s recommended you at least know the basics of HTML.
  • Database management systems DBMS for database powered applications.
  • For more advanced topics such as interactive applications and web services, you will need JavaScript and XML.

The flowchart diagram shown below illustrates the basic architecture of a PHP web application and how the server handles the requests.

Why use PHP?

You have obviously heard of a number of programming languages out there; you may be wondering why we would want to use PHP as our poison for the web programming. Below are some of the compelling reasons.

  • PHP is open source and free.
  • Short learning curve compared to other languages such as JSP, ASP etc.
  • Large community document
  • Most web hosting servers support PHP by default unlike other languages such as ASP that need IIS. This makes PHP a cost effective choice.
  • PHP is regular updated to keep abreast with the latest technology trends.
  • Other benefit that you get with PHP is that it’s a server side scripting language; this means you only need to install it on the server and client computers requesting for resources from the server do not need to have PHP installed; only a web browser would be enough.
  • PHP has in built support for working hand in hand with MySQL; this doesn’t mean you can’t use PHP with other database management systems. You can still use PHP with
    • Postgres
    • Oracle
    • MS SQL Server
    • ODBC etc.
  • PHP is cross platform; this means you can deploy your application on a number of different operating systems such as windows, Linux, Mac OS etc.

What is PHP used for & Market share

In terms of market share, there are over 20 million websites and application on the internet developed using PHP scripting language.

This may be attributed to the points raised above;

The diagram below shows some of the popular sites that use PHP


PHP File Extensions

File extension and Tags In order for the server to identify our PHP files and scripts, we must save the file with the “.php” extension. Older PHP file extensions include

  • .phtml
  • .php3
  • .php4
  • .php5
  • .phps

The PHP tags themselves are not case-sensitive, but it is strongly recommended that we use lower case letter. The code below illustrates the above point.

<?php … ?>

We will be referring to the PHP lines of code as statements. PHP statements end with a semi colon (;). If you only have one statement, you can omit the semi colon. If you have more than one statement, then you must end each line with a semi colon. For the sake of consistency, it is recommended that you always end your statement(s) with a semi colon.  PHP scripts are executed on the server. The output is returned in form of HTML.

How to run PHP?

Manual installation of a Web server and PHP requires in-depth configuration knowledge but the XAMPP suite of Web development tools, created by Apache Friends, makes it easy to run PHP. Installing XAMPP on Windows only requires running an installer package without the need to upload everything to an online Web server. This PHP Tutorial gives you an idea of XAMPP and how it is used for executing the PHP programs.

What is XAMPP?

It is a free and open-source cross-platform webserver solution stack package developed by Apache Friends that consists of the Apache HTTP Server, MariaDB & MySQL database, and interpreters for scripts are written in the PHP and Perl programming languages. XAMPP stands for Cross-Platform (X), Apache (A), MariaDB & MySQL (M), PHP (P) and Perl (P). It is a simple, lightweight Apache distribution that makes it extremely easy for developers to create a local web server for testing and deployment purposes.

PHP using WAMP Server

If you’re working on a project for the production environment and have a PC running the Windows OS then you should opt for WAMP server because it was built with security in mind. You can use this method to run PHP scripts you may have obtained from somewhere and need to run with little or no knowledge of PHP. You can execute your scripts through a web server where the output is a web browser.

Let’s have a look at the steps involved in using WAMP Server:

  1. Install the Server Software
  2. Set up the Server
  3. Save PHP Scripts
  4. Run PHP Scripts
  5. Troubleshoot

Now let’s move ahead with our PHP Tutorial and find out the suitable IDE for PHP.

PHP IDE

In order to remain competitive and productive, writing good code in minimum time is an essential skill that every software developer must possess. As the number and style of writing code increases and new programming languages emerge frequently, it is important that the software developers must opt for the right IDE to achieve the objectives.

An Integrated Development Environment or IDE is a self-contained package that allow you to write, compile, execute and debug code in the same place. So let’s have a look at some of the best IDE’s for PHP:

  • PHPStorm
  • Netbeans
  • Aptana Studio
  • Eclipse
  • Visual Code Editor
  • ZendStudio

PHP Hello world

The program shown below is a basic PHP application that outputs the words “Hello World!” When viewed in a web browser.

<?php

echo "Hello world";

?>

Output:

Hello world