-
Notifications
You must be signed in to change notification settings - Fork 0
PHP
- PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages.
- PHP is an acronym for "Hypertext Preprocessor"
- PHP files can contain text, HTML, CSS, JavaScript, and PHP code
PHP is a general-purpose language. When it comes to the purpose of the programming languages, there are two main types: domain-specific and general-purpose languages. The domain-specific languages are used within specific application domains. For example, SQL is a domain-specific language. It’s used mainly for querying data from relational databases. And SQL cannot be used for other purposes. On the other hand, PHP is a general-purpose language because PHP can develop various applications.
PHP is a cross-platform language. PHP can run on all major operating systems, including Linux, Windows, and macOS.
You can use PHP with all leading web servers such as Nginx, OpenBSD, and Apache.
Some cloud environments also support PHP like Microsoft Azure and Amazon AWS.
PHP is quite flexible. It’s not just limited to processing HTML. PHP has built-in support for generating PDF, GIF, JPEG, and PNG images. You can also output any text, such as XHTML and XML.
One notable feature of PHP is that it supports many databases, including MySQL, PostgreSQL, MS SQL, db2, Oracle Database, and MongoDB.
PHP has two main applications:
Server-side scripting – PHP is well-suited for developing dynamic websites and web applications.
Command-line scripting – like Python and Perl, you can run PHP script from the command line to perform administrative tasks like sending emails and generating PDF files.
How PHP works:
First, the web browser sends an HTTP request to the web server
Second, the PHP preprocessor locates the web server, processes PHP code to generate the HTML document.
Third, the web server sends the HTML document back to the web browser.
- install a web server
- install PHP
- install a database, such as MySQL
Typically, you won’t install all this software separately because connecting them is tricky and not intended for beginners.
Therefore, it’s easier to find an all-in-one software package that includes PHP, a web server, and a database server. One of the most popular PHP development environments is XAMPP.
XAMPP is an easy install Apache distribution that contains PHP, MariaDB, and Apache webserver. XAMPP supports Windows, Linux, and macOS.
To install XAMPP on windows, you can go to the XAMPP official website and download the suitable version for your platform.
A PHP script starts with
A PHP script can be placed anywhere in the document.
PHP statements end with a semicolon (;).
In PHP, keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined functions are not case-sensitive. However; all variable names are case-sensitive!
<!DOCTYPE html>
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
</html>
A comment in PHP code is a line that is not executed as a part of the program. Its only purpose is to be read by someone who is looking at the code.
Comments can be used to:
- Let others understand your code
- Remind yourself of what you did - Comments can remind you of what you were thinking when you wrote the code
- Leave out some parts of your code
// This is a single-line comment
# This is also a single-line comment
/* This is a
multi-line comment */
The multi-line comment syntax can also be used to prevent execution of parts inside a code-line:
$x = 5 /* + 15 */ + 5;
echo $x;
Variables are "containers" for storing information.
In PHP, a variable starts with the $ sign, followed by the name of the variable:
$x = 5;
$y = "John"
In the example above, the variable $x will hold the value 5, and the variable $y will hold the value "John".
When you assign a text value to a variable, put quotes around the value.
Unlike other programming languages, PHP has no command for declaring a variable. It is created the moment you first assign a value to it.
A variable can have a short name (like $x and $y) or a more descriptive name ($age, $carname, $total_volume).
Rules for PHP variables:
- A variable starts with the $ sign, followed by the name of the variable
- A variable name must start with a letter or the underscore character
- A variable name cannot start with a number
- A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
- Variable names are case-sensitive ($age and $AGE are two different variables)
The PHP echo statement is often used to output data to the screen.
$txt = "W3Schools.com";
echo "I love $txt!";
# or
echo "I love " . $txt . "!";
$x = 5;
$y = 4;
echo $x + $y;
You can assign the same value to multiple variables in one line:
$x = $y = $z = "Fruit";
PHP is a loosley typed language. You do not have to tell it what datatype a variable is. The datatype depends on the value of the variable.
PHP automatically associates a data type to the variable, depending on its value. Since the data types are not set in a strict sense, you can do things like adding a string to an integer without causing an error.
In PHP 7, type declarations were added. This gives an option to specify the data type expected when declaring a function, and by enabling the strict requirement, it will throw a "Fatal Error" on a type mismatch.
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 referenced/used.
PHP has three different variable scopes:
- local
- global
- static
A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function:
$x = 5; // global scope
function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
echo "<p>Variable x outside function is: $x</p>";
A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function:
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
// using x outside the function will generate an error
echo "<p>Variable x outside function is: $x</p>";
You can have local variables with the same name in different functions, because local variables are only recognized by the function in which they are declared.
The global
keyword is used to access a global variable from within a function.
To do this, use the global keyword before the variables (inside the function):
$x = 5;
$y = 10;
function myTest() {
global $x, $y;
$y = $x + $y;
}
myTest();
echo $y; // outputs 15
PHP also stores all global variables in an array called $GLOBALS[index]. The index holds the name of the variable. This array is also accessible from within functions and can be used to update global variables directly.
The example above can be rewritten like this:
$x = 5;
$y = 10;
function myTest() {
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}
myTest();
echo $y; // outputs 15
Normally, when a function is completed/executed, all of its variables are deleted. However, sometimes we want a local variable NOT to be deleted. We need it for a further job.
To do this, use the static keyword when you first declare the variable:
function myTest() {
static $x = 0;
echo $x;
$x++;
}
myTest(); // 0
myTest(); // 1
myTest(); // 2
Then, each time the function is called, that variable will still have the information it contained from the last time the function was called.
With PHP, there are two basic ways to get output: echo and print.
echo has no return value while print has a return value of 1 so it can be used in expressions.
echo can take multiple parameters (although such usage is rare) while print can take one argument.
echo is marginally faster than print.
The echo statement can be used with or without parentheses: echo
or echo()
.
echo "<h2>PHP is Fun!</h2>";
echo "Hello world!<br>";
echo "I'm about to learn PHP!<br>";
echo "This ", "string ", "was ", "made ", "with multiple parameters.";
The print statement can be used with or without parentheses: print or print().
$txt1 = "Learn PHP";
$txt2 = "W3Schools.com";
$x = 5;
$y = 4;
print "<h2>" . $txt1 . "</h2>";
print "Study PHP at " . $txt2 . "<br>";
print $x + $y;
PHP supports the following data types:
- String
- Integer
- Float (floating point numbers - also called double)
- Boolean
- Array
- Object
- NULL
- Resource
To get the data type of a variable, use the var_dump()
function.
A string is a sequence of characters.
A string can be any text inside quotes. You can use single or double quotes:
var_dump("John"); // string(4) "John"
There is a big difference between double quotes and single quotes in PHP.
Double quotes process special characters, E.g. when there is a variable in the string, it returns the value of the variable.
Single quoted strings does not perform such actions, it returns the string like it was written, with the variable name:
<?php
$x = "John";
echo "Hello $x"; // Hello John
echo 'Hello $x'; // Hello $x
?>
An integer data type is a non-decimal number between -2,147,483,648 and 2,147,483,647.
Rules for integers:
- An integer must have at least one digit
- An integer must not have a decimal point
- An integer can be either positive or negative
- Integers can be specified in: decimal (base 10), hexadecimal (base 16), octal (base 8), or binary (base 2) notation
var_dump(5); // int(5)
A float (floating point number) is a number with a decimal point or a number in exponential form.
var_dump(3.14); // float(3.14)
A Boolean represents two possible states: TRUE or FALSE.
$x = true;
var_dump($x); // bool(true)
An array stores multiple values in one single variable.
In the following example $cars is an array. The PHP var_dump() function returns the data type and value:
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
/*
array(3) {
[0]=>
string(5) "Volvo"
[1]=>
string(3) "BMW"
[2]=>
string(6) "Toyota"
}
*/
Classes and objects are the two main aspects of object-oriented programming.
A class is a template for objects, and an object is an instance of a class.
When the individual objects are created, they inherit all the properties and behaviors from the class, but each object will have different values for the properties.
Let's assume we have a class named Car that can have properties like model, color, etc. We can define variables like $model, $color, and so on, to hold the values of these properties. When the individual objects (Volvo, BMW, Toyota, etc.) are created, they inherit all the properties and behaviors from the class, but each object will have different values for the properties.
If you create a __construct()
function, PHP will automatically call this function when you create an object from a class.
class Car {
public $color;
public $model;
public function __construct($color, $model) {
$this->color = $color;
$this->model = $model;
}
public function message() {
return "My car is a " . $this->color . " " . $this->model . "!";
}
}
$myCar = new Car("red", "Volvo");
var_dump($myCar); // object(Car)#1 (2) { ["color"]=> string(3) "red" ["model"]=> string(5) "Volvo" }
Null is a special data type which can have only one value: NULL
.
A variable of data type NULL is a variable that has no value assigned to it.
If a variable is created without a value, it is automatically assigned a value of NULL.
Variables can also be emptied by setting the value to NULL:
$x = "Hello world!";
$x = null;
var_dump($x); // NULL
If you assign an integer value to a variable, the type will automatically be an integer. If you assign a string to the same variable, the type will change to a string:
$x = 5;
var_dump($x);
$x = "Hello";
var_dump($x);
If you want to change the data type of an existing variable, but not by changing the value, you can use casting. Casting allows you to change data type on variables:
$x = 5;
var_dump($x); // int(5)
$x = (string) $x;
var_dump($x); // string(1) "5"
The special resource type is not an actual data type. It is the storing of a reference to resources external to PHP.
Resources are typically created and managed by external libraries or extensions, and they provide a way for PHP to interact with resources outside of its typical data types like integers, strings, and arrays.
Some common examples of resources include file handles, database connections, image representations, and more. When you work with functions or extensions that deal with external resources, they often return a resource type, and you use this resource handle to manipulate or interact with the underlying resource.
Here is an example using the fopen function, which opens a file and returns a file handle resource:
<?php
// Open a file for reading
$fileHandle = fopen("example.txt", "r");
// Check if the file handle is a resource
if (is_resource($fileHandle)) {
echo "File opened successfully.";
// Read the content of the file
$content = fread($fileHandle, filesize("example.txt"));
echo "File content: " . $content;
// Close the file handle
fclose($fileHandle);
} else {
echo "Failed to open the file.";
}
?>
The PHP strlen()
function returns the length of a string.
<?php
echo strlen("Hello world!"); // 12
?>
The PHP str_word_count()
function counts the number of words in a string.
<?php
echo str_word_count("Hello world!"); // 2
?>
The PHP strpos()
function searches for a specific text within a string.
If a match is found, the function returns the character position of the first match. If no match is found, it will return FALSE.
The first character position in a string is 0
<?php
echo strpos("Hello world!", "world"); // 6
?>
PHP has a set of built-in functions that you can use to modify strings
The strtoupper()
function returns the string in upper case:
$x = "Hello World!";
echo strtoupper($x); // HELLO WORLD!
?>
The strtolower()
function returns the string in lower case:
<?php
$x = "Hello World!";
echo strtolower($x); // hello world!
?>
The PHP str_replace()
function replaces some characters with some other characters in a string.
Replace the text "World" with "Dolly":
<?php
$x = "Hello World!";
echo str_replace("World", "Dolly", $x); // Hello Dolly!
?>
The PHP strrev()
function reverses a string.
<?php
$x = "Hello World!";
echo strrev($x); // !dlroW olleH
?>
The trim()
removes any whitespace from the beginning or the end:
<?php
$x = " Hello World! ";
echo trim($x); // 'Hello World!'
?>
The PHP explode()
function splits a string into an array.
The first parameter of the explode() function represents the "separator". The "separator" specifies where to split the string.
The separator is required.
Use the space character as separator:
<?php
$x = "Hello World!";
$y = explode(" ", $x);
//Use the print_r() function to display the result:
print_r($y);
/*
Result:
Array ( [0] => Hello [1] => World! )
*/
?>
To concatenate, or combine, two strings you can use the . operator:
<?php
$x = "Hello";
$y = "World";
$z = $x . $y;
echo $z;
?>
//HelloWorld
You can add a space character like this:
<?php
$x = "Hello";
$y = "World";
$z = $x . " " . $y;
echo $z;
?>
// Hello World
An easier and better way is by using the power of double quotes.
By surrounding the two variables in double quotes with a white space between them, the white space will also be present in the result:
<?php
$x = "Hello";
$y = "World";
$z = "$x $y";
echo $z;
?>
// Hello World
Slicing: You can return a range of characters by using the substr()
function. Specify the start index and the number of characters you want to return.
Start the slice at index 6 and end the slice 5 positions later:
<?php
$x = "Hello World!";
echo substr($x, 6, 5); // World
?>
The first character has index 0.
By leaving out the length parameter, the range will go to the end:
<?php
$x = "Hello World!";
echo substr($x, 6); // World!
?>
Use negative indexes to start the slice from the end of the string:
<?php
$x = "Hello World!";
echo substr($x, -5, 3);
?>
The last character has index -1.
Use negative length to specify how many characters to omit, starting from the end of the string.
Get the characters starting from the "W" in "World" (index 5) and continue until 3 characters from the end.
<?php
$x = "Hello World!";
echo substr($x, 5, -3); // Wor
?>
Escape Character
To insert characters that are illegal in a string, use an escape character.
An escape character is a backslash \
followed by the character you want to insert.
An example of an illegal character is a double quote inside a string that is surrounded by double quotes:
<?php
$x = "We are the so-called \"Vikings\" from the north.";
echo $x; // We are the so-called "Vikings" from the north.
?>
- ' - Single Quote Description: Represents a single quote within a string.
$str = 'This is a single quote: \' within a string.';
echo $str;
// Output: This is a single quote: ' within a string.
- " - Double Quote Description: Represents a double quote within a string.
$str = "This is a double quote: \" within a string.";
echo $str;
// Output: This is a double quote: " within a string.
- $ - PHP Variables Description: Represents the dollar sign $ within a string, preventing the interpretation of a variable.
$name = "John";
$str = "Hello, my name is \$name.";
echo $str;
// Output: Hello, my name is $name.
- \n - New Line Description: Represents a new line character.
$str = "This is the first line.\nThis is the second line.";
echo $str;
// Output:
// This is the first line.
// This is the second line.
- \r - Carriage Return Description: Represents a carriage return character.
$str = "This is before.\rThis is after.";
echo $str;
// Output: This is after.before.
- \t - Tab Description: Represents a tab character.
``php $str = "First column\tSecond column\tThird column"; echo $str; // Output: First column Second column Third column
7. \f - Form Feed
Description: Represents a form feed character.
```php
$str = "This is before.\fThis is after.";
echo $str;
// Output: This is before.
// This is after.
- \ooo - Octal Value Description: Represents a character based on its octal value.
$str = "\110\145\154\154\157"; // Octal values for 'Hello'
echo $str;
// Output: Hello
- \xhh - Hex Value Description: Represents a character based on its hexadecimal value.
Copy code
$str = "\x48\x65\x6C\x6C\x6F"; // Hex values for 'Hello'
echo $str;
// Output: Hello