PHP Syntax: A Complete Guide For Beginners -w9school

PHP is a server-side scripting language. Enclosed in <?php ?> tags, it handles variables, loops, conditionals, functions, arrays, objects, and integrates with HTML for dynamic web content.

PHP Syntax: A Complete Guide For Beginners -w9school

PHP Syntax

PHP (Hypertext Preprocessor) is a widely used server-side scripting language for web development. It's embedded within HTML code and executed on the server, generating dynamic web content.

Here's an overview of PHP syntax:

Tags and Output:

  • PHP code is enclosed within tags.

  • The semicolon is used to conclude PHP statements. 

Example

echo "Hello, World!";
?>

Variables:

  • Variables start with a dollar sign ('$') and are case-sensitive.

Example

$name = "John";

Data Types:

  • Strings: Enclosed in single or double quotes.

  • Integers: Whole numbers.

  • Floats: Decimal numbers.

  • Booleans: true or false.

  • Arrays: Indexed or associative collections of values.

  • Objects: Instances of user-defined classes.

  • Null: Represents a null value.

Strings:

  • Concatenation using the '.' operator, or interpolation within double-quoted strings.

Example

$message = "Hello, " . $name;

Operators:

  • PHP supports arithmetic, comparison, logical, and assignment operators.

Example

$sum = $a + $b;
$is_equal = ($a == $b);

Conditional Statements:

  • 'if', 'else if', and 'else' control structures for decision-making.

Example

if ($age < 18) {
    echo "You're a minor.";
} else {
    echo "You're an adult.";
}

Loops:

PHP provides various loop types: 'for', 'while', 'do-while', and 'foreach'.

Example

for ($i = 0; $i < 5; $i++) {
    echo $i;
}

Functions:

  • User-defined functions encapsulate code for reuse.

Example

function greet($name) {
    return "Hello, " . $name;
}

Arrays:

  • Indexed and associative arrays are widely used.

Example

$colors = array("red", "green", "blue");
$person = array("name" => "Alice", "age" => 30);

Superglobals:

  • Special arrays like '$_GET', '$_POST', and '$_SESSION' store data from forms and sessions.

Include and Require:

  • Including external PHP files using 'include' or require.

Example

include "header.php";

Classes and Objects:

  • PHP supports object-oriented programming with classes and objects.

Example

class Car {
    public $brand;
    
    function startEngine() {
        echo "Engine started!";
    }
}

Exception Handling:

  • Try-catch blocks are used for handling exceptions.

Example

try {
    // Some code that might throw an exception
} catch (Exception $e) {
    echo "An error occurred: " . $e->getMessage();
}

Comments:

  • Single-line comments using // and multi-line comments using '/*' */'.

Example

// This is a single-line comment

/*
This is a
multi-line comment
*/

Remember that this is just a brief overview of PHP syntax. PHP has a vast array of functions, libraries, and advanced features for various web development tasks. It's recommended to refer to official PHP documentation or tutorials for more in-depth understanding and examples.

Basic PHP Syntax

On the server, a PHP script is run, and the outcome is transmitted back to the browser as plain HTML.

Anywhere in the document is a good spot to insert a PHP script.

PHP scripts begin with the syntax :

Example

// PHP code goes here
?>

".php" is the standard PHP file extension. 

HTML tags and a little amount of PHP scripting code are commonly seen in PHP files.

Here's an example of a basic PHP file with a PHP script that uses the built-in PHP function "echo" to produce the word "Hello World!" on a web page:

Example

<!DOCTYPE html>
<html>
<body>

<h1>My first PHP page</h1>

echo "Hello World!";
?>


</body>
</html>

Remember that PHP statements conclude with a semicolon (;).

PHP Case Sensitivity

In PHP, case is not taken into account when using keywords, classes, functions, or user-defined functions (such as 'if', 'else', 'while', 'echo', etc.).

All three of the echo statements in the following example are equal and legitimate:

Example

<!DOCTYPE html>
<html>
<body>

ECHO "Hello World!
"
;
echo "Hello World!
"
;
EcHo "Hello World!
"
;
?>


</body>
</html>

Please keep in mind that all variable names are case-sensitive!

The value of the '$color' variable will only be displayed in the first sentence of the example below! This is because to the fact that '$color', '$COLOR', and '$coLOR' are each regarded as a separate variable:

Example

<!DOCTYPE html>
<html>
<body>

$color = "red";
echo "My car is " . $color . "
"
;
echo "My house is " . $COLOR . "
"
;
echo "My boat is " . $coLOR . "
"
;
?>


</body>
</html>

Comments in PHP

A line of PHP code that is not run as part of the program is referred to as a comment. It exists just to be read by a person who is studying the code.One can utilize comments for:

  • Allow others to comprehend your coding

  • Remind yourself of your actions – The majority of programmers have had the experience of revisiting their own work a year or two later and having to retrace their steps.

  • Comments serve as a reminder of your thoughts at the time you authored the code.

PHP offers a number of commenting options:

Example

Syntax for single-line comments:

<!DOCTYPE html>
<html>
<body>

// This is a single-line comment

# There is only one line in this comment. 

?>

</body>
</html>

Example

Syntax for multiple-line comments:

<!DOCTYPE html>
<html>
<body>

/*
This comment block has several lines.
that spans over multiple
lines
*/

?>


</body>
</html>

Example

Using comments to omit code from the file:

<!DOCTYPE html>
<html>
<body>

// Additionally, comments can be used to exclude portions of a code line.
$x = 5 /* + 15 */ + 5;
echo $x;
?>


</body>
</html>

PHP Variables

PHP variables are used to store and manipulate data. They are preceded by a dollar sign ('$') and can contain letters, numbers, and underscores, but must start with a letter or underscore. Variables are case-sensitive.

Here are examples of variable declarations and usage:

Example

$name = "John";       // String
$age = 30;            // Integer
$height = 5.9;        // Float
$isStudent = true;    // Boolean
$colors = array("red", "green", "blue");  // Array

// Concatenation
$message = "My name is " . $name . " and I'm " . $age . " years old.";

// Variable interpolation within double-quoted strings
$message = "My name is $name and I'm $age years old.";

Variables can store various data types, and their values can be manipulated, displayed, and used in calculations within PHP code.The "containers" for storing information are variables.

Creating (Declaring) PHP Variables

A variable in PHP begins with the '$' sign, followed by the variable name:

Example

Following the execution of the aforementioned statements, the variables '$tx't, '$x', and '$y' will each contain the values Hello world!, 5, and 10.5 respectively.

Reminder: Always enclose text values in quotes when assigning them to variables.

Notably, PHP lacks a command for declaring variables in contrast to other programming languages. As soon as you first give it a value, it is created.

Consider variables to be storage spaces for data.

PHP Variables 

A variable's name might be short (like x and y) or longer (like age, carname, or total_volume).PHP variable rules:

  • The dollar sign ($) and the variable's name come first in a variable.

  • The underscore character or a letter must come first in a variable name.

  • No number may begin a variable name.

  • Only underscores (A-z, 0-9, and _) and alphanumeric characters are permitted in variable names.

  • The capitalization of variable names ($age and $AGE are two distinct variables)

Keep in mind that case matters when using variable names in PHP.

Output Variables

When displaying data on the screen, the PHP 'echo' command is frequently utilized.

The example that follows will demonstrate how to print text and a variable:

Example

The output from the following example will be the same as that from the previous example:

The total of two variables will be displayed in the example below:

A loosely typed language is PHP.

Note that we did not need to inform PHP of the variable's data type in the example above.

Depending on the value of the variable, PHP automatically assigns a data type to it. Due to the fact that the data types are not tightly defined, it is feasible to add a string to an integer without encountering any difficulties. Type declarations were added in PHP 7. By selecting the stringent requirement, it will throw a "Fatal Error" on a type mismatch and provides the opportunity to define the data type anticipated when declaring a function.

PHP Variables Scope

Variable declarations in PHP are allowed at any point in the script.A variable's scope is the area of the script where it can be used or referenced.

There are three distinct variable scopes in PHP:

  • local

  • global

  • static

Global and Local Scope

The only place a variable declared outside of a function can be accessed is outside of that function and has a GLOBAL SCOPE:

Example

Variable with global scope:

$x = 5; // global scope

function myTest() {
  // using x inside this function will generate an error
  echo "

Variable x inside function is: $x ";
}
myTest();

echo "

Variable x outside function is: $x ";
?>

A variable declared within a function has a LOCAL SCOPE and can be accessed exclusively from within that function:

Example

Variable with local scope:

function myTest() {
  $x = 5// local scope
  echo "

Variable x inside function is: $x ";
}
myTest();

// using x outside the function will generate an error
echo "

Variable x outside function is: $x ";
?>

Since local variables are only recognized by the function in which they are declared, you can have local variables with the same name in many functions.

PHP The global Keyword

To access a global variable from within a function, use the 'global' keyword.

To accomplish this, place the global keyword (inside the function) before the variables:

Example

$x = 5;
$y = 10;

function myTest() {
  global $x, $y;
  $y = $x + $y;
}

myTest();
echo $y; // outputs 15
?>

Additionally, PHP keeps track of all global variables in the array '$GLOBALS[index]'. The variable name is stored in the index. This array can be used to directly update global variables and is also reachable from within methods.

The above illustration can be rewritten as follows:

Example

$x = 5;
$y = 10;

function myTest() {
  $GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}

myTest();
echo $y; // outputs 15
?>

PHP The static Keyword

Normally, all of a function's variables are removed when it has been finished or run.

However, there are situations when we want a local variable to remain in place. It is required for a different task.

Use the 'static' keyword when you first declare the variable to do this:

Example

function myTest() {
  static $x = 0;
  echo $x;
  $x++;
}

myTest();
myTest();
myTest();
?>

After that, each time the function is called, the data from the previous call will still be there in that variable.

Note that the variable is still specific to the function.

What's Your Reaction?

like

dislike

love

funny

angry

sad

wow