PHP

What is PHP?

PHP (Hypertext Preprocessor) is a widely-used, open-source programming language especially suited for web development. It’s a server-side scripting language, which means the code runs on the web server rather than on the user’s browser.

What is a PHP File?

What Can PHP Do?

Key Features of PHP:

Why PHP?

Basic PHP Syntax

PHP Case Sensitivity

Comments

PHP Variables

Creating (Declaring) PHP Variables

Rules for PHP variables

Output Variables

The dot operator (.) is used to concatenate strings or variables together in PHP.

PHP Variables Scope

PHP has three different variable scopes:

1. Local

	
			//Example:
			<?php
				function myTest() {
					$x = 5; // local scope
					echo "<p>Variable x inside function is: $x</p>";
				}
			
				myTest();
				
				//Using x outside the function will cause an error: Undefined variable
				echo "<p>Variable x outside function is: $x</p>";
			?>
		

2. Global

Using global Keyword Inside Functions:

Using $GLOBALS Inside Functions:

3. Static

A static variable inside a function retains its value across multiple calls. Normally, a local variable is reset each time the function is called. By declaring it static, the variable keeps its previous value.

PHP echo and print Statements

			<?php
				$txt1 = "Learn PHP";
				$txt2 = "W3Schools.com";
				$x = 5;
				$y = 4;

				echo "<h2>" . $txt1 . "</h2>";
				echo "Study PHP at " . $txt2 . "<br>";
				echo $x + $y . "<br>";
			  	echo "This ", "string ", "was ", "made ", "with multiple parameters.";

				print "<h2>" . $txt1 . "</h2>";
				print "Study PHP at " . $txt2 . "<br>";
				print $x + $y;
			?>
		

PHP Data Types

PHP supports the following data types:

PHP String Function

PHP Numbers

PHP Integers

PHP has the following functions to check if the type of a variable is integer:
			<?php
				$x = 5985;
				var_dump(is_int($x));

				$x = 59.85;
				var_dump(is_int($x));
			?>
		

PHP Floats

PHP has the following functions to check if the type of a variable is float:

PHP Infinity

A numeric value that is larger than PHP_FLOAT_MAX is considered infinite.
PHP has the following functions to check if a numeric value is finite or infinite:
			<?php
				$x = 1.9e411;
				var_dump($x);
				echo "<br>";
			        var_dump(is_infinite($x));
			?>
		

PHP NaN

NaN stands for Not a Number.
PHP has the following functions to check if a value is not a number:
			<?php
				$x = acos(8);
				var_dump(is_nan($x));
			?>
		

PHP Numerical Strings

			<?php
				$x = 5985;
				var_dump(is_numeric($x));

				$x = "5985";
				var_dump(is_numeric($x));

				$x = "59.85" + 100;
				var_dump(is_numeric($x));

				$x = "Hello";
				var_dump(is_numeric($x));
			?>
		

PHP Constants

PHP Constant Arrays

			<?php
				define("cars", [
   				"Alfa Romeo",
    				"BMW",
    				"Toyota"
				]);
				echo cars[0];
			?>
		
Note: Constants are automatically global and can be used across the entire script.

PHP Operators

PHP divides the operators in the following groups:

PHP Arithmetic Operators

Operator Name Example
+ Addition $x + $y
- Subtraction $x - $y
* Multiplication $x * $y
/ Division $x / $y
% Module $x % $y
** Exponentiation $x ** $y

PHP Assignment Operators

Assignment same as
x = y x = y
x += y x = x+ y
x -= y x = x - y
x *= y x = x*y
x /= y x = x/y
x %= y x = x%y

PHP Comparison Operators

Operator Name Example Result
== Equal $x == $y Returns true if $x is equal to $y
=== Identical $x === $y Returns true if $x is equal to $y, and they are of the same type
!= Not Equal $x != $y Returns true if $x is not equal to $y
<> Not equal $x <> $y Returns true if $x is not equal to $y
!== Not Identical $x !== $y Returns true if $x is not equal to $y, or they are not of the same type
> Greater than $x > $y Returns true if $x is greater than $y
> Less than $x < $y Returns true if $x is less than $y
>= Greater than or equal to $x >= $y Returns true if $x is greater than or equal to $y
<= Less than or equal to $x <= $y Returns true if $x is less than or equal to $y
<=> Spaceship $x <=> $y Returns an integer less than, equal to, or greater than zero, depending on if $x is less than, equal to, or greater than $y. Introduced in PHP 7.
			<!DOCTYPE html>
			<html>
			<body>

			<?php
				$x = 5;  
				$y = 10;

				echo ($x <=> $y); // returns -1 because $x is less than $y
				echo "<br>";

				$x = 10;  
				$y = 10;

				echo ($x <=> $y); // returns 0 because values are equal
				echo "<br>";

				$x = 15;  
				$y = 10;

				echo ($x <=> $y); // returns +1 because $x is greater than $y
			?>

			</body>
			</html>
		

Common Use Cases: Sorting

Example 1: Sorting an array of numbers using an arrow function

			$arr = [3, 1, 4, 2];
			
			// Print each item before sorting
			echo "Before sorting: <br>";
			foreach ($arr as $item) {
			    echo $item . "<br>";
			}
			
			// Sort the array using usort and a lambda function
			// usort() stands for "user-defined sort".
			usort($arr, fn($a, $b) => $a <=> $b); //This sorts the array $arr in ascending order
			
			// Print each item after sorting
			echo "After sorting: <br>";
			foreach ($arr as $item) {
			    echo $item . "<br>";
			}
		

Example 2: Sorting an array of objects using an arrow function

			// Define a simple class
			class Product {
			    public $name;
			    public $price;
			
			    public function __construct($name, $price) {
			        $this->name = $name;
			        $this->price = $price;
			    }
			}
			
			// Create an array of Product objects
			$products = [
			    new Product("Apple", 2.50),
			    new Product("Banana", 1.20),
			    new Product("Cherry", 3.578),
			    new Product("Date", 2.00)
			];
			
			// Sort by price (ascending) using an arrow function
			usort($products, fn($a, $b) => $a->price <=> $b->price);
			
			// Display sorted products
			echo "Sorted by price (ascending):<br>";
			foreach ($products as $product) {
			    echo $product->name . " - $" . number_format($product->price, 2) . "<br>";
			}
		

To sort by name instead, simply change the comparator:

			usort($products, fn($a, $b) => strcmp($a->name, $b->name));
		

Sorting by multiple criteria

			// Sort by price, then by name
			usort($products, fn($a, $b) =>
			    $a->price <=> $b->price ?: strcmp($a->name, $b->name)
			);
		

PHP Increment / Decrement Operators

Operator Name Description
++$x Pre-increment Increments $x by one, then returns $x
$x++ Post-increment Returns $x, then increments $x by one
--$x Pre-decrement Decrements $x by one, then returns $x
$x-- Post-decrement Returns $x, then decrements $x by one

PHP Logical Operators

Operator Name Example Result
and And $x and $y True if both $x and $y are true
or Or $x or $y True if either $x or $y is true
xor Xor $x xor $y True if either $x or $y is true, but not both
&& And $x && $y True if both $x and $y are true
|| Or $x || $y True if either $x or $y is true
! Not !$x True if $x is not true

PHP String Operators

Operator Name Example Result
. Concatenation $txt1 . $txt2 Concatenation of $txt1 and $txt2
.= Concatenation assignment $txt1 .= $txt2 Appends $txt2 to $txt1

PHP Array Operators

Operator Name Example Result
+ Union $x + $y Union of $x and $y
== Equality $x == $y Returns true if $x and $y have the same key/value pairs
=== Identity $x === $y Returns true if $x and $y have the same key/value pairs in the same order and of the same types
!= Inequality $x != $y Returns true if $x is not equal to $y
<> Inequality $x <> $y Returns true if $x is not equal to $y
!== Non-identity $x !== $y Returns true if $x is not identical to $y

Reference

www.w3schools.com