Contents

Basic Concepts

PHP Syntax

PHP Overview: A Beginner’s Guide to Syntax

PHP is a versatile server-side language widely used in web development. Its straightforward syntax makes it suitable for both beginners and advanced developers. In this guide, we will explore the basic syntax of PHP. PHP scripts can be embedded within HTML using special PHP tags.

Basic PHP Syntax

PHP code is executed between PHP tags. The most commonly used tags are <?php ... ?>, which mark the beginning and end of PHP code. This is known as Escaping to PHP.

				
					<?php
    // PHP code goes here
?>

				
			

These tags, also known as Canonical PHP tags, indicate to the PHP parser which parts of the document to process. Everything outside these tags is treated as plain HTML. Each PHP command must end with a semicolon (;).

PHP Syntax Example

				
					<?php
    // Using echo to display a message
    echo "Greetings from PHP!";
?>

				
			

Output:

				
					Greetings from PHP!

				
			
Embedding PHP in HTML

You can embed PHP code within an HTML document using PHP tags. In this example, the <?php echo "Welcome to PHP!"; ?> dynamically adds content into the HTML.

				
					<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>PHP Example</title>
</head>
<body>
    <h1><?php echo "Welcome to PHP!"; ?></h1>
</body>
</html>

				
			

Output:

				
					Welcome to PHP!

				
			
Short PHP Tags

Short tags allow for a more compact syntax, starting with <? and ending with ?>. This feature works only if the short_open_tag setting in the php.ini configuration file is enabled.

				
					<?
    echo "Short tag in action!";
?>

				
			

Output:

				
					Short tag in action!

				
			
Case Sensitivity in PHP

PHP is partly case-sensitive:

  • Keywords (such as if, else, while, echo) are not case-sensitive.
  • Variables are case-sensitive.

Example:

				
					<?php
    $Message = "Hello, Developer!";
    
    // Outputs: Hello, Developer!
    echo $Message; 
    
    // Error: Undefined variable $message
    echo $message;
?>

				
			

Output:

				
					Hello, Developer!
Notice: Undefined variable: message

				
			
Comments in PHP

Comments help make the code easier to understand and maintain. They are ignored by the PHP engine.

  • Single-Line Comments: Single-line comments are brief explanations added with // or #.
				
					<?php
    // This is a single-line comment
    echo "Single-line comment example!";
    
    # This is another single-line comment
?>

				
			

Output:

				
					Single-line comment example!

				
			
  • Multi-Line Comments: Multi-line comments span several lines, beginning with /* and ending with */.
				
					<?php
    /* This is a multi-line comment.
       PHP variables start with a $ sign.
    */
    
    $message = "Learning PHP!";
    echo $message;
?>

				
			

Output:

				
					Learning PHP!

				
			
Variables and Data Types

Variables store data and are defined with the $ symbol followed by the variable name.

Declaring Variables: Variables are created by assigning a value using the assignment operator (=).

				
					$name = "Alice";   // String
$age = 25;         // Integer
$isStudent = false; // Boolean

				
			

Data Types in PHP

PHP supports multiple data types:

  • String: A sequence of characters.
  • Integer: Whole numbers.
  • Float: Numbers with decimal points.
  • Boolean: True or false values.
  • Array: A collection of values.
  • Object: An instance of a class.
  • NULL: A variable with no value.
  • Resource: A reference to external resources like database connections.

Code Blocks in PHP

PHP allows grouping of multiple statements into a block using curly braces ({}). A block is typically used with conditions or loops.

				
					<?php
    $num = 10;
    
    if ($num > 0) {
        echo "Number is positive.\n";
        echo "It is greater than zero.";
    }
?>

				
			

Output:

				
					Number is positive.
It is greater than zero.

				
			

PHP Variables

PHP Variables are one of the core concepts in programming. They are used to store information that can be utilized and altered throughout your code. PHP variables are straightforward, dynamically typed (meaning there’s no need to explicitly declare their type), and crucial for building dynamic, interactive web applications.

Declaring Variables in PHP

To define a variable in PHP, simply assign a value to it using the $ symbol followed by the variable name. Variable names are case-sensitive and must start with either a letter or an underscore, followed by any combination of letters, numbers, or underscores.

Example:

				
					<?php
    $fullName = "John Doe";  // String
    $years = 25;             // Integer
    $price = 1999.99;        // Float
    $isActive = false;       // Boolean
?>

				
			
Variable Naming Conventions

When working with variables in PHP, it’s important to follow best practices to ensure your code remains clean and readable:

1. Start with a Letter or Underscore: Variable names must begin with either a letter or an underscore, not a number.
2. Use Descriptive Names: Make sure the variable name clearly describes its purpose, e.g., $customerName, $totalPrice.
3. Case Sensitivity: Remember that variable names are case-sensitive in PHP, so $count and $Count are treated as two distinct variables.
4. Avoid Reserved Keywords: Avoid using PHP reserved keywords (e.g., class, function) as variable names.

Example of Valid and Invalid Variable Names:

				
					<?php
    $userID = 101;        // Valid
    $_total = 1500;       // Valid

    $1stPrize = "Gold";   // Invalid: Cannot start with a number
    $default = "Active";  // Valid, but best to avoid reserved keywords
?>

				
			
PHP Data Types
  • Integer: Whole numbers, either positive or negative, without decimal points.
  • Float: Numbers with decimal points or those in exponential notation.
  • NULL: Represents a variable that has no value.
  • String: A sequence of characters, enclosed in single or double quotes.
  • Boolean: Holds one of two possible values: true or false.
  • Array: A collection of multiple values, stored in a single variable.
  • Object: An instance of a class.
  • Resource: Special variables holding references to external resources, like database connections.
PHP Variable Scope

Variable scope determines where a variable can be accessed in your code. PHP variables can have local, global, static, or superglobal scope.

1. Local Scope (Local Variables): Variables defined inside a function are local to that function and cannot be accessed outside it. A variable defined outside the function with the same name remains a separate variable.

Example:

				
					<?php
    $counter = 100;

    function demoLocalScope() {
        // Local variable inside the function
        $counter = 50;
        echo "Local variable inside the function: $counter \n";
    }

    demoLocalScope();
    echo "Global variable outside the function: $counter \n";
?>

				
			

Output:

				
					Local variable inside the function: 50
Global variable outside the function: 100

				
			

2. Global Scope (Global Variables): Variables declared outside a function have global scope and can be accessed directly outside the function. To access them inside a function, use the global keyword.

Example:

				
					<?php
    $value = 42;

    function demoGlobalScope() {
        global $value;
        echo "Global variable inside the function: $value \n";
    }

    demoGlobalScope();
    echo "Global variable outside the function: $value \n";
?>

				
			

Output:

				
					Global variable inside the function: 42
Global variable outside the function: 42

				
			

3. Static Variables: In PHP, local variables are destroyed after the function finishes execution. If you need a variable to retain its value across multiple function calls, use the static keyword.

Example:

				
					<?php
    function demoStaticVariable() {
        static $count = 1;
        $temp = 10;

        $count++;
        $temp++;

        echo "Static count: $count \n";
        echo "Local temp: $temp \n";
    }

    demoStaticVariable();
    demoStaticVariable();
?>

				
			

Output:

				
					Static count: 2
Local temp: 11
Static count: 3
Local temp: 11

				
			

4. Superglobals: Superglobals are built-in arrays in PHP, accessible throughout the script (even inside functions). Common examples include $_GET, $_POST, $_SESSION, $_COOKIE, $_SERVER, and $_GLOBALS.

Example:

				
					<?php
    // Using the $_SERVER superglobal to get the current script's file name
    echo "Current file: " . $_SERVER['PHP_SELF'];
?>

				
			

Output:

				
					Current file: /path/to/current/script.php

				
			
Variable Variables

PHP allows dynamic variable names, known as “variable variables.” These are variables whose names are created dynamically by the value of another variable.

Example:

				
					<?php
    $city = 'capital';
    $$city = 'Paris'; // Equivalent to $capital = 'Paris';

    echo $capital; // Outputs: Paris
?>

				
			

Output:

				
					Paris

				
			

PHP echo and print

PHP echo and print are two commonly used language constructs for displaying data on the screen. Since they are language constructs rather than functions, parentheses are not required (though parentheses can be used with print). Both constructs are frequently employed for printing strings, variables, and HTML content in PHP scripts.

  • echo: Generally faster and capable of outputting multiple strings separated by commas.
  • print: Slightly slower, returns a value of 1, and can only take one argument at a time.
PHP echo Statement

The echo construct is simple to use and doesn’t behave like a function, meaning parentheses are not necessary. However, they can be included if desired. The echo statement ends with a semicolon (;). It allows you to display one or more strings, numbers, variables, or results of expressions.

Basic Syntax of echo

Without parentheses:

				
					echo "Hello, World!";

				
			

With parentheses (though optional):

				
					echo("Hello, World!");

				
			

Displaying Variables with echo

We can use echo to easily output variables, numbers, and results of expressions.

Example:

				
					<?php
    // Declaring variables
    $greeting = "Welcome to PHP!";
    $x = 15;
    $y = 25;

    // Outputting variables and expressions
    echo $greeting . "\n";
    echo $x . " + " . $y . " = ";
    echo $x + $y;
?>

				
			

Output:

				
					Welcome to PHP!
15 + 25 = 40

				
			

In the above code, the dot (.) operator is used for concatenation, and \n is used to insert a new line.

Displaying Strings with echo

You can use echo to print strings directly.

Example:

				
					<?php
    echo "PHP is a popular scripting language!";
?>

				
			

Output:

				
					PHP is a popular scripting language!

				
			

Displaying Multiple Strings with echo

You can pass multiple arguments to the echo statement, separating them with commas.

Example:

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

				
			

Output:

				
					Hello from PHP!
				
			
PHP print Statement

The print construct is similar to echo and is often used interchangeably. Like echo, it does not require parentheses, but can use them optionally. Unlike echo, print can only output a single argument and always returns a value of 1.

Basic Syntax of print

Without parentheses:

				
					print "Learning PHP is fun!";

				
			

With parentheses:

				
					print("Learning PHP is fun!");

				
			

Output:

				
					x && y: false
x || y: true

				
			

Displaying Variables with print

You can display variables with print in the same way as with echo.

Example:

				
					<?php
    // Declaring variables
    $message = "PHP is awesome!";
    $num1 = 30;
    $num2 = 40;

    // Outputting variables and expressions
    print $message . "\n";
    print $num1 . " + " . $num2 . " = ";
    print $num1 + $num2;
?>

				
			

Output:

				
					PHP is awesome!
30 + 40 = 70

				
			

Displaying Strings with print

You can print strings with print in a similar way to echo, but only one string can be printed at a time.

Example:

				
					<?php
    print "PHP makes web development easier!";
?>

				
			

Output:

				
					PHP makes web development easier!

				
			
Difference Between echo and print Statements in PHP

While both echo and print are used to display data, there are a few key differences between them:

S.Noechoprint
1.Can take multiple arguments separated by commas.Only accepts one argument.
2.Does not return any value.Always returns a value of 1.
3.Displays multiple strings or values in one statement.Can only display one string or value.
4.Slightly faster than print.Slightly slower than echo.

PHP Data Types

PHP data types are an essential concept that defines how variables store and manage data. PHP is a loosely typed language, meaning that variables do not require a specific data type to be declared. PHP supports eight different types of data, which are discussed below.

Predefined Data Types

1. Integer: Integers represent whole numbers, both positive and negative, without any fractional or decimal parts. They can be written in decimal (base 10), octal (base 8), or hexadecimal (base 16). By default, numbers are assumed to be in base 10. Octal numbers are prefixed with 0 and hexadecimal numbers with 0x. PHP integers must be within the range of -2^31 to 2^31.

Example:

				
					<?php

// Declaring integers in different bases
$dec = 100;    // decimal
$oct = 010;    // octal
$hex = 0x1A;   // hexadecimal

$sum = $dec + $oct + $hex;
echo "Sum of integers: $sum\n";

// Returns data type and value
var_dump($sum);
?>

				
			

Output:

				
					Sum of integers: 126
int(126)

				
			

2. Float (Double): Floats (or doubles) represent numbers with decimal points or in exponential notation. They can handle both positive and negative values. In PHP, float and double are synonymous.

Example:

				
					<?php

$float1 = 35.75; 
$float2 = 44.30; 

$sum = $float1 + $float2;

echo "Sum of floats: $sum\n";

// Returns data type and value
var_dump($sum);
?>

				
			

Output:

				
					Sum of floats: 80.05
float(80.05)

				
			

3. String: Strings hold sequences of characters. They can be enclosed within either double quotes (") or single quotes ('). The key difference between them is how PHP handles variable interpolation and escape sequences.

Example:

				
					<?php

$name = "John";
echo "The name is $name\n";   // Double quotes allow variable parsing
echo 'The name is $name';     // Single quotes treat $name as literal text
echo "\n";

// Returns data type, length, and value
var_dump($name);
?>

				
			

Output:

				
					The name is John
The name is $name
string(4) "John"

				
			

4. Boolean: Booleans are used in conditional statements and can only take two values: TRUE or FALSE. In PHP, non-empty values are treated as TRUE, while 0, NULL, and empty strings are considered FALSE.

Example:

				
					<?php

$isValid = TRUE;
$isFalse = FALSE;

if ($isValid) {
    echo "This statement is true.\n";
}

if ($isFalse) {
    echo "This statement is false.\n";    // This won't be executed
}
?>

				
			

Output:

				
					This statement is true.

				
			
User-Defined (Compound) Data Types

1. Array: Arrays in PHP can store multiple values under a single name. These values can be of different data types, making arrays versatile.

Example:

				
					<?php

$fruits = array("Apple", "Banana", "Orange");

echo "First fruit: $fruits[0]\n";
echo "Second fruit: $fruits[1]\n";
echo "Third fruit: $fruits[2]\n\n";

// Returns data type and value
var_dump($fruits);
?>

				
			

Output:

				
					First fruit: Apple
Second fruit: Banana
Third fruit: Orange

array(3) {
  [0]=>
  string(5) "Apple"
  [1]=>
  string(6) "Banana"
  [2]=>
  string(6) "Orange"
}

				
			

2. Objects: Objects are instances of classes. They allow you to create complex data structures that can hold both values and methods for processing data. Objects are explicitly created using the new keyword.

Example:

				
					<?php

class Car {
    public $model;
    
    function __construct($model) {
        $this->model = $model;
    }

    function displayModel() {
        return "Car model: " . $this->model;
    }
}

$car = new Car("Toyota");
echo $car->displayModel();
?>

				
			

Output:

				
					Car model: Toyota

				
			
Special Data Types

1. NULL: The NULL data type represents a variable that has no value. Variables are automatically assigned NULL if they have not been initialized or explicitly set to NULL.

Example:

				
					<?php

$var = NULL;

echo "Value of the variable is: ";
echo $var;    // This will produce no output

// Returns data type and value
var_dump($var);
?>

				
			

Output:

				
					Value of the variable is:
NULL

				
			

2. Resources: Resources are special variables that hold references to external resources such as database connections or file handles. These are not actual data types in PHP but rather references.

Note: Resource examples typically involve external connections like databases or files, so examples will depend on external setups.

PHP Functions to Check Data Types

PHP provides several functions to verify the data type of a variable:

  • is_int(): Checks if a variable is an integer.
  • is_string(): Checks if a variable is a string.
  • is_array(): Checks if a variable is an array.
  • is_object(): Checks if a variable is an object.
  • is_bool(): Checks if a variable is a boolean.
  • is_null(): Checks if a variable is NULL.

Example:

				
					<?php

$val = 100;

if (is_int($val)) {
    echo "The variable is an integer.\n";
}

$txt = "Hello!";
if (is_string($txt)) {
    echo "The variable is a string.\n";
}
?>

				
			

Output:

				
					The variable is an integer.
The variable is a string.

				
			

PHP Strings

PHP Strings

Strings are among the most important data types in PHP. They are used to handle and manipulate text data, process user inputs, and create dynamic content. PHP offers a variety of functions and methods for working with strings, making it easy to display and modify text.

A string is essentially a sequence of characters. PHP strings can consist of letters, numbers, symbols, and special characters. They are widely used for input/output handling, dynamic content generation, and more.

Declaring Strings in PHP

Strings in PHP can be declared using four different syntaxes: single quotes, double quotes, heredoc, and nowdoc.

1. Single Quotes: Single quotes in PHP are used to define simple strings. Text within single quotes is treated literally, meaning special characters and variables inside them are not interpreted.

				
					<?php
// Single Quote String
$greeting = 'Hello, Code World!';
echo $greeting;
?>

				
			

Output:

				
					Hello, Code World!

				
			

In this case, the string is printed as is.

However, note how the following example works:

				
					<?php
// Single Quote String
$language = 'PHP';
echo 'Learning $language is fun!';
?>

				
			

Output:

				
					Learning $language is fun!

				
			

In this case, the variable $language is not processed because single-quoted strings do not recognize variables.

2. Double Quotes: Double-quoted strings, on the other hand, do recognize variables and special characters.

				
					class Test {
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            System.out.println(i);  // Loop variable i
        }
        
        int i = 20;  // Declare i after the loop
        System.out.println(i);  // Access new i outside the loop
    }
}

				
			

Output:

				
					Hello, Code Enthusiasts!
Learning PHP is exciting!

				
			

In this example, double quotes allow variable substitution, and the \n special character is interpreted as a new line.

3. Heredoc Syntax: Heredoc (<<<) is a way to declare a string in PHP without enclosing it in quotes. It behaves similarly to a double-quoted string, allowing variable interpolation and escape sequences.

				
					<?php
$description = <<<DOC
Welcome to the world of coding.
This is the best way to learn PHP!
DOC;

echo $description;
?>

				
			

Output:

				
					Welcome to the world of coding.
This is the best way to learn PHP!

				
			

4. Nowdoc Syntax: Nowdoc syntax is similar to heredoc, but it behaves like a single-quoted string—no variables or escape sequences are processed.

				
					<?php
$description = <<<'DOC'
Welcome to PHP.
Enjoy coding!
DOC;

echo $description;
?>

				
			

Output:

				
					Welcome to PHP.
Enjoy coding!

				
			
Key Built-in PHP String Functions

1. strlen() Function: This function returns the length of the string.

				
					<?php
echo strlen("Code is powerful!");
?>

				
			

Output:

				
					17

				
			

2. strrev() Function: This function reverses the string.

				
					<?php
echo strrev("Coding is fun!");
?>

				
			

Output:

				
					!nuf si gnidoC

				
			

3. str_replace() Function: This function replaces all occurrences of a string within another string.

				
					<?php
echo str_replace("fun", "challenging", "Coding is fun!");
?>

				
			

Output:

				
					Coding is challenging!

				
			

4. strpos() Function: This function searches for a string within another string and returns its starting position.

				
					<?php
echo strpos("Coding is enjoyable", "enjoyable"), "\n";
echo strpos("Learning PHP", "PHP"), "\n";
var_dump(strpos("Learning Python", "JavaScript"));
?>

				
			

Output:

				
					9
9
bool(false)

				
			

5. trim() Function: This function removes characters or spaces from both sides of a string.

				
					<?php
echo strpos("Coding is enjoyable", "enjoyable"), "\n";
echo strpos("Learning PHP", "PHP"), "\n";
var_dump(strpos("Learning Python", "JavaScript"));
?>

				
			

Output:

				
					Hello World!

				
			

6. explode() Function: This function breaks a string into an array based on a delimiter.

				
					<?php
echo strpos("Coding is enjoyable", "enjoyable"), "\n";
echo strpos("Learning PHP", "PHP"), "\n";
var_dump(strpos("Learning Python", "JavaScript"));
?>

				
			

Output:

				
					Array
(
    [0] => PHP
    [1] => is
    [2] => great
    [3] => for
    [4] => web
    [5] => development
)

				
			

7. strtolower() Function: This function converts a string to lowercase.

				
					<?php
echo strtolower("HELLO WORLD!");
?>

				
			

Output:

				
					hello world!

				
			

8. strtoupper() Function: This function converts a string to uppercase.

				
					<?php
echo strtoupper("hello world!");
?>

				
			

Output:

				
					HELLO WORLD!

				
			

9. str_word_count() Function: This function counts the number of words in a string.

				
					<?php
echo str_word_count("PHP makes web development easy");
?>

				
			

Output:

				
					5