What is PHP.

PHP (Hypertext Preprocessor) is known as a general-purpose scripting language that can be used to develop dynamic and interactive websites. It was among the first server-side languages that could be embedded into HTML, making it easier to add functionality to web pages without needing to call external files for data.
Pros
It’s open source (and therefore free!)
It’s versatile: One of the major benefits of PHP is that it is platform independent, meaning it can be used on Mac OS, Windows, Linux and supports most web browsers. It also supports all the major web servers, making it easy to deploy on different systems and platforms at minimal additional cost.
It’s fast and secure: Two things that every organization wants their website or application to be are fast and secure. PHP uses its own memory and competes well on speed
It is well connected with databases: PHP makes it easy to connect securely with almost any kind of database. This gives developers more freedom when choosing which database is best suited for the application being built.
PHP Vs Other
JavaScript: This remains the most popular programming language of them all, and has been around for almost as long as PHP.
JavaScript is primarily a client-side language, and therefore not directly comparable with PHP, though the rise of Node.js and other frameworks enables developers to write server-side scripts with JavaScript.
but On the other hand, PHP is easier to learn and maintain, so using it could mean lower development costs.
Python: is one of the most popular languages around today, loved for its simplicity and flexibility. It has emerged as the number one choice for data science and AI, though still trails far behind PHP in use for web development.it is flexible, though does not yet provide the same level of database connectivity and support as PHP.
Ruby: Ruby is another open-source language that has been around since the 90s, and is used in the popular web development framework ‘Ruby on Rails’. It is praised for its elegant syntax and robust performance, though it is considered more complicated to learn than PHP and doesn’t have the same extensive community support.

Datatypes in PHP


String.
Integer.
Float (floating point numbers - also called double)
Boolean.
Array.
Object.
NULL.
Resource.

Boolean : A Boolean represents two possible states: TRUE or FALSE.
$x = true;
$y = false;

Float

A float (floating point number) is a number with a decimal point or a number in exponential form. In the following example $x is a float. The PHP var_dump() function returns the data type and value:
?php
$x = 10.365;
var_dump($x);
?>

Integer

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.

String

A string is a sequence of characters, like "Hello world!". A string can be any text inside quotes. You can use single or double quotes:
?php
$x = "Hello world!";
$y = 'Hello world!';
echo $x;
echo "
";
echo $y;
?>

Array


An array stores multiple values in one single variable.
?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>

PHP Arrays


The array() function is used to create an array.PHP array() function creates and returns an array. It allows you to create indexed, associative and multidimensional arrays.
In PHP, there are three types of arrays:
Indexed arrays - with numeric index
Associative arrays - Arrays with named keys
Multidimensional arrays - Arrays containing one or more arrays
<
Indexed Arrays
Syntax for indexed arrays:
array(value1, value2, value3, etc.)

Associative Arrays

Syntax for associative arrays:
array(key=>value,key=>value,key=>value,etc.)
Create an associative array named $age:
?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old."; //Peter is 35 years old.
?>

Multidimensional Arrays

Create a multidimensional array:
?php
// A two-dimensional array:
$cars=array
(
array("Volvo",100,96),
array("BMW",60,59),
array("Toyota",110,100)
);
?>
Output :
Volvo: Ordered: 100. Sold: 96
BMW: Ordered: 60. Sold: 59
Toyota: Ordered: 110. Sold: 100

faster in PHP & HTML


On average, pure HTML is executed quicker than PHP. However, it won't be that much quicker if there's nothing really dynamic with regards to the content you're pulling in.
PHP is better than HTML as it is more powerful in terms of its usage. Given below are the differences: PHP is a scripting language that can generate dynamic web pages as the code execution takes place on the server and the result is returned by the server in HTML format which is displayed by the browser.

PHP a scripting language.


Yes, PHP is a scripting language used mainly for server-side web development. Because of its open-source nature, PHP is a general-purpose language often used for other projects and graphical user interfaces.
PHP is Scripting language because we can embed php code into HTML. If code of programming language can emmbed with other language or integrate with other language or script called scipting language. PHP is server side language because php requires server to run a code.

PHP Applications


While PHP is largely used as a scripting language for web-based applications, it is also possible to employ it for creating desktop graphical user interface.
PHP scripts can be used on most of the well-known operating systems like Linux, Unix, Solaris, Microsoft Windows, MAC OS and many others. It also supports most web servers including Apache and IIS. Using PHP affords web developers the freedom to choose their operating system and web server.

Xampp Server


XAMPP is an abbreviation for cross-platform, Apache, MySQL, PHP and Perl, and it allows you to build WordPress site offline, on a local web server on your computer. 
Apache , tomcat r web servers.Mysql - a database server.
Filezilla to transfer files from 1 host to another host.
Xampp is a platform to provide us the access of apache web server locally . There r also other platform like Xampp eg... Wamp,Mamp,Lamp but xampp is very popular as it can be seamlessly use with windows, mac,linux etc . without any extra configuration.
Apache here is used for php.we 1st start the apache than for db we start mysql. Apache web server is open source written in C.
Mysql connection through Xampp ->
Open your XAMPP Control Panel and click on the “Admin” button of the MySQL section, which will lead you to the phpMyADmin page.
Alternatively, you can reach this page by typing http://localhost/phpmyadmin/
Localhost - 127.0.0.1 -> Loop back address
localhost is a hostname that refers to the current device used to access it. Localhost is an alias used to refer to IP addresses reserved for loopback. 
PhpMyAdmin - tool written in php used to handle the administration of mysql over the web.
htdocs - is a static directory of our web server eg...apache server

Variable Conventions


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.
The names of your variables cannot contain special characters such as & , % , # , or @ .
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )

Single Quotes Vs Double Quotes


Single or double quotes in PHP programming are used to define a string. But, there are lots of differences between these two.
Single-quoted Strings: It is the easiest way to define a string. You can use it when you want the string to be exactly as it is written. All the escape sequences like \r or \n, will be output as specified instead of having any special meaning.
Single-quote is usually faster in some cases. The special case is that if you to display a literal single-quote, escape it with a backslash (\) and if you want to display a backslash, you can escape it with another backslash (\\).
Double-quoted strings: By using Double quotes the PHP code is forced to evaluate the whole string. The main difference between double quotes and single quotes is that by using double quotes, you can include variables directly within the string. It interprets the Escape sequences. Each variable will be replaced by its value.

PHP Logical operator


Logical operators perform logical operations on TRUE and FALSE. Values used with a logical operator are converted into booleans prior to being evaluated. For numerical values, zero will be interpreted as FALSE, and other values will be TRUE. Empty strings are considered be FALSE, and any nonempty string is TRUE
PHP divides the operators in the following groups:
Arithmetic operators
Assignment operators
Comparison operators
Increment/Decrement operators
Logical operators
String operators
Array operators
Conditional assignment operators

Printing ways in PHP


The basic functions for displaying output in PHP are as follows:
Print() Function.
Echo() Function.
Printf() Function.
Sprintf() Function.
Var_dump() Function.
Print_r() Function.

print() : Print() Function - Using this function we can display the outputs in the browser. This function returns the Boolean value true. We cannot print the multiple statements using this function. The print function plays the same role as the echo function.
print - Unlike echo, print accepts only one argument at a time. The print outputs only the strings. It is slow compared to that of echo.
?php
print "Welcome Vineet Kumar Saini !!";
?>
Output: Welcome Vineet Kumar Saini !!

echo


The echo() function outputs one or more strings. Using this function we can display multiple statements in the browser. The echo() function is slightly faster than print(). Because it won't return a value.
echo - no value or returns void. It display the outputs one or more strings separated by commas.
echo has no return value while print has a return value of 1 so it can be used in expressions. ?php
echo "Welcome Vineet Kumar Saini !!";
?>
Output:Welcome Vineet Kumar Saini !!

The printf() function is also used in C, C++. The printf() function outputs a formatted string. Using this function we can display the output with the help of the formats specified.
?php
$name="Vineet Saini";
$age=24;
printf("The age of %s is %d years.",$name,$age);
?>

print_r()


The Print_r() PHP function is used to return an array in a human readable form. This function displays the elements of an array and properties of an object. The print_r() function displays human-readable information about a variable.
print_r - outputs the detailed information about the parameter in a format with its type (of an array or an object).Similar to var_dump().
?php
$arr=array ("Vineet","Kumar","Saini");
$arr1=array(10,20,30);
print_r($arr);
print_r($arr1);
?>
Output : Array([0]=>Vineet [1]=>Kumar [2]=>Saini)
Array([0]=>10 [1]=>20 [2]=>30)

The sprintf() writes a formatted string to a variable. This is the same as printf, but instead of displaying the output on the web page, it returns that output. sprintf() prints the result to a string.
?php
$name="Vineet Saini";
$age=24;
$rv=sprintf ("The age of %s is %d years.",$name, $age);
echo $rv;
?>

var_dump()


The var_dump() function displays information of a variable that includes its type and value. This function displays the variable value along with the variable data type. The var_dump() function is used to display structured information (type and value) about one or more variables.
print_r() & var_dump -  can't return any value it can only dump/print the values . The returned value of print_r will be in string format.
?php
$name="Vineet Saini";
$age=24;
var_dump($name);
var_dump($age);
?>
Output: string(!2) "Vineet Saini" int(24)
The var_dump() function displays structured information about variables/expressions including its type and value. shows in-depth details, by providing additional details of data type of the value (including the descendant elements) number of elements in a variable length of the value
array(5) { [0]=> string(3) "xyz"
[1]=> bool(false)
[2]=> bool(true)
[3]=> int(100)
[4]=> array(1) { [0]=> string(2) "50" } }

== vs ===operator


The assignment equality = operator only assigns values. The equality == does not assign values, but compares them without checking their data types. The triple equals sign operator === won't do assignment, but will check for equality of values and the data type.
The == operator does the type conversion of the operands before comparison, whereas the === operator compares the values as well as the data types of the operands.
The comparison operator called as the Identical operator is the triple equal sign “===”. This operator allows for a much stricter comparison between the given variables or values. This operator returns true if both variable contains same information and same data types otherwise return false

PHP Functions


A function is a block of statements that can be used repeatedly in a program. It will not execute automatically when a page loads. and it will be executed by a call to the function.
There are 2 types of functions under PHP -
Built-in Function : PHP has over 1000 built-in functions that can be called directly, from within a script, to perform a specific task.
Some are like -
Array
Calendar
Date
Directory
Error
Exception
Filesystem
Filter
FTP
JSON
Keywords
Mail
Math
MySQLi
User-defined Function : Syntax
function functionName() {
code to be executed;
}

PHP Array Function


These functions allow interacting with and manipulating arrays in various ways. Arrays are essential for storing, managing, and operating on sets of variables.
array() - Create an array
array_chunk() - Splits an array into chunks of arrays
array_diff() - Compares array values, and returns the differences
array_fill() - Fills an array with values
array_intersect() - Compares array values, and returns the matches
array_merge() - Merges one or more arrays into one array
array_pop($arr) :array_pop() pops and returns the value of the last element of array , shortening the array by one element. This function will reset() the array pointer of the input array after use.
Example :
?php
$a=array("red","green","blue");
array_pop($a);
print_r($a);
?>
Output :
Array ( [0] => red [1] => green )

array_push($arr,$val)


The array_push() function inserts one or more elements to the end of an array. You can add one value, or as many as you like. Note: Even if your array has string keys, your added elements will always have numeric keys .
Example:
$classTenSubjects = array(1=>'Mathematics',2=>'Physics',3=>'Chemistry',4=>'English');
//pushing elements
array_push($classTenSubjects,"Hindi","Yoga");
Output
Array ( [1] => Mathematics [2] => Physics [3] => Chemistry [4] => English [5] => Hindi [6] => Yoga )

array_shift($arr)


The array_shift() function removes the first element from an array, and returns the value of the removed element. If the keys are numeric, all elements will get new keys, starting from 0 and increases by 1 .
Example :
?php
$a=array(0=>"red",1=>"green",2=>"blue");
echo array_shift($a);
print_r ($a);
?>
Output :
red
Array ( [0] => green [1] => blue )

array_unshift($arr,$val)


The array_unshift() function inserts new elements to an array. The new array values will be inserted in the beginning of the array. You can add one value, or as many as you like. Note: Numeric keys will start at 0 and increase by 1.
Example :
?php
$a=array("a"=>"red","b"=>"green");
array_unshift($a,"blue");
print_r($a);
?>
Output :
Array ( [0] => blue [a] => red [b] => green )

Ways of including 1 PHP file


There are two PHP functions which can be used to included one PHP file into another PHP file.
The include() Function.
The require() Function.
include - The include() function takes all the text in a specified file and copies it into the file that uses the include function. If there is any problem in loading a file then the include() function generates a warning but the script will continue execution.
Syntax : ?php include("menu.php"); ?>
The include and require statements are identical, except upon failure: require will produce a fatal error (E_COMPILE_ERROR) and stop the script. include will only produce a warning (E_WARNING) and the script will continue.

require


The require() function takes all the text in a specified file and copies it into the file that uses the include function. If there is any problem in loading a file then the require() function generates a fatal error and halt the execution of the script.
So there is no difference in require() and include() except they handle error conditions. It is recommended to use the require() function instead of include(), because scripts should not continue executing if files are missing or misnamed.
Syntax: ?php require("xxmenu.php"); ?>
The require_once expression is identical to require except PHP will check if the file has already been included, and if so, not include (require) it again.

include_once


The include_once keyword is used to embed PHP code from another file. If the file is not found, a warning is shown and the program continues to run. If the file was already included previously, this statement will not include it again.
Syntax : ?php include_once 'footer.php';?>
The include_once statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include statement, with the only difference being that if the code from a file has already been included, it will not be included again, and include_once returns true .

require_once


The require_once keyword is used to embed PHP code from another file. If the file is not found, a fatal error is thrown and the program stops. If the file was already included previously, this statement will not include it again.
Syntax : ?php require_once 'footer.php';?>
require and require_once throw a fatal error if the file is not found, whereas include and include_once only show a warning and continue to load the rest of the page.

In-built function in PHP


Built-in functions are ones for which the compiler generates inline code at compile time. Every call to a built-in function eliminates a runtime call to the function having the same name in the dynamic library.
Built-in functions are the functions that are provided by PHP to make programming more convenient.
explode() :The explode() function breaks a string into an array.but the "separator" parameter cannot be an empty string.
Example :
?php
$str = "Hello world. It's a beautiful day.";
print_r (explode(" ",$str));
?>
Output :
Array ( [0] => Hello [1] => world. [2] => It's [3] => a [4] => beautiful [5] => day. )

implode()


Implode in PHP is a function that is used to concatenate all the elements of an array together in the same order as they are in the array. And it, in turn, returns a new resultant string. This function is the same as the join() function in PHP
Example :
?php
$arr = array('Hello','World!','Beautiful','Day!');
echo implode(" ",$arr);
?>
Output :
Hello World! Beautiful Day!

The explode() function breaks a string into an array, but the implode function returns a string from the elements of an array.

strlen()


The strlen() function returns the length of a string.The strlen() is a built-in function in PHP which returns the length of a given string. It takes a string as a parameter and returns its length. It calculates the length of the string including all the whitespaces and special characters.
Syntax:
strlen($string);

str_word_count()


The str_word_count() function counts the number of words in a string.The str_word_count() function is a built-in function in PHP and is used to return information about words used in a string like total number word in the string, positions of the words in the string etc.
Syntax :
?php
$mystring = "Twinkle twinkl4e little star";
print_r(str_word_count($mystring));
?>
Output :
5

pow()


The pow() is a PHP mathematic function. It raises the first number to the power of the second number.
The pow() function in PHP is used to calculate a base raised to the power of exponent. It is a generic function which can be used with number raised to any value.It takes two parameters which are the base and exponent and returns the desired answer. If both the arguments passed are non-negative integers and the result can be represented as an integer, the result is returned with integer type, otherwise, it is returned as a float.
Syntax :
number pow($base, $exp)

rand()


The rand() function generates a random integer.If you want a random integer between 10 and 100 (inclusive), use rand (10,100).
Example :
?php
echo(rand() . "
");
echo(rand() . "
");
echo(rand(10,100));
?>
Output :
512549293
1132363175
79

str_replace()


The str_replace() function replaces some characters with some other characters in a string. This function works by the following rules:
If the string to be searched is an array, it returns an array.
If the string to be searched is an array, find and replace is performed with every array element.
Example :
?php
echo str_replace("world","Peter","Hello world!");
?>
Output :
Hello Peter!

sort()


The sort() function sorts an indexed array in ascending order. Use the rsort() function to sort an indexed array in descending order.
Different sorting function : sort() - arrays in ascending order
rsort() - sort arrays in descending order
asort() - sort associative arrays in ascending order, according to the value
ksort() - associative arrays in ascending order, according to the key
arsort() - sort associative arrays in descending order, according to the value
krsort() - sort associative arrays in descending order, according to the key
Example :
?php
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);
?>
Output :
BMW Toyota Volvo

array_merge()


The array_merge in PHP is a built-in function that combines two or more arrays into a single array. This function combines the elements or values from two or more arrays into a single array. The values of one array are appended to the end of the previous array during the merging process.
Example :
?php
$a1=array("red","green");
$a2=array("blue","yellow");
print_r(array_merge($a1,$a2));
?>
Output :
red,green,blue ,yellow

array_unique()


The array_unique() function removes duplicate values from an array. If two or more array values are the same, the first appearance will be kept and the other will be removed.
Example :
?php
$a=array("a"=>"red","b"=>"green","c"=>"red");
print_r(array_unique($a));
?>
Output :
Array ( [a] => red [b] => green )
Avoid array_unique as much as possible and it will speed up your code execution. You may use the array_count_values, as it is the fastest code, but it is also possible to use other fast alternatives :
foreach with array_keys, or array_flip

count()


The count() function returns the number of elements in an array.
Example :
?php
$cars=array("Volvo","BMW","Toyota");
echo count($cars);
?>
Output :
3

How to make Database connection in PHP


Database connection using MySQLi Object-Oriented
?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$conn->close();//CLOSE THE CONNECTION
?>
Database connection using MySQLi Procedural
?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
mysqli_close($conn);//CLOSE THE CONNECTION
?>
Database connection using PDP
?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
$conn = null;//CLOSE THE CONNECTION
?>

MySQLi Vs PDO


Both MySQLi and PDO have their advantages:
PDO will work on 12 different database systems, whereas MySQLi will only work with MySQL databases.
So, if you have to switch your project to use another database, PDO makes the process easy. You only have to change the connection string and a few queries. With MySQLi, you will need to rewrite the entire code - queries included.
Both are object-oriented, but MySQLi also offers a procedural API.
Both support Prepared Statements. Prepared Statements protect from SQL injection, and are very important for web application security.

Session in PHP


A session is a way to store information (in variables) to be used across multiple pages. Unlike a cookie, the information is not stored on the users computer.
When you work with an application, you open it, do some changes, and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are or what you do, because the HTTP address doesn't maintain state.
Session variables solve this problem by storing user information to be used across multiple pages (e.g. username, favorite color, etc). By default, session variables last until the user closes the browser.
So; Session variables hold information about one single user, and are available to all pages in one application.
$_SESSION is an associative array that contains all session variables. It is used to set and get session variable values.
Start a session from 1 php file :
?php
// Start the session
session_start();
?>
DOCTYPE html>
html>
body>
?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
Get PHP Session Variable Values
?php
session_start();
?>
!DOCTYPE html>
html>
body>
?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".
";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
show all the session variable values for a user session
?php
session_start();
?>
!DOCTYPE html>
html>
body>
?php
print_r($_SESSION);
?>

header in PHP


The header in PHP is a PHP built-in function for sending a raw HTTP header. The HTTP functions are those that manipulate information sent by the webserver to the client or browser before it sends any further output. The header() function in PHP sends a raw HTTP header to a client or browser.

When we develop restful apis using php than we sometimes also have to pass some additional information called header information.
header('Content-Type: application/json')
//the data returned by the application is in main format
header('Access-Control-Allow-Methods:PUT')
//The type of restful method we r going to use
header('Access-Control-Allow-Origin: *')
//this header is related with security. If we r passing * than it means anyone
can use my api in their application. If we want to give access of my api to any particular website than I have to give it's name in place of *
header('Access-Control-Allow-Headers:
')
//Also related with security. Instead of giving multiple headers separately we can give those headers under header name which will reduce the risk of hacking of our website because hacker won't allow to pass any header in it by themselves.

Basically, there are two types of header calls. One is header which starts with string “HTTP/” used to figure out the HTTP status code to send. Another one is the “Location” which is mandatory.