Introduction of PHP programming

PHP started out as a small open-source design that evolved as further and further people set up how useful it was. Rasmus Lerdorf unleashed the first interpretation of PHP way back in 1994.

PHP PROGRAMMING

PHP PROGRAMMING

  • PHP is a recursive acronym for” PHP Hypertext Preprocessor”.
  • PHP is a garçon side scripting language that’s bedded in HTML. It’s used to manage dynamic content, databases, session shadowing, and indeed make entire-commerce spots.
  • It’s integrated with a number of popular databases, including MySQL, PostgreSQL, Oracle, Sybase, Informix, and Microsoft SQL Garçon.
  • PHP is pleasingly zippy in its prosecution, especially when collected as an Apache module on the Unix side. The MySQL garçon, formerly started, executes indeed veritably complex queries with huge result sets in record-setting time.
  • PHP supports a large number of major protocols similar to POP3, IMAP, and LDAP. PHP4 added support for Java and distributed object infrastructures( COM and CORBA), making n- league development a possibility for the first time.
  • PHP is forgiving PHP language tries to be as forgiving as possible.
  • PHP Syntax is C- Like.
PHP PROGRAMMING
PHP PROGRAMMING
PHP PROGRAMMING
PHP PROGRAMMING

Versions & Inventions

PHP, which stands for Hypertext Preprocessor, is a popular programming language used for web development. It has evolved over the years with various versions and introduced new features and enhancements. Here are some key versions and notable inventions in PHP:

  1. PHP 3.
  2. PHP 4.
  3. PHP 5.
  4. PHP 5.3.
  5. PHP 5.4.
  6. PHP 5.5.
  7. PHP 5.6.
  8. PHP 7.
  9. PHP 7.1, 7.2, 7.3, 7.4, and 8.

PHP tools

  1. phpstorm
  2. NetBeans
  3. Cloud9 IDE
  4. Sublime Text
  5. Xdebug
  6. PHPUnit
  7. Behat

PHP Software Requirement

The PHP Community Provides Some types of Software Garçon result under The GNU( General Public License).

These are the following:
1. WAMP Server
2. LAMP Server
3. MAMP Server
4. XAMPP Server

PHP with other technologies

The most common are XAMPP( Windows, Apache Garçon, MySQL, Perl, and PHP) and Beacon( Linux, Apache, MySQL, PHP). As PHP is platform-independent, it’s veritably easy to integrate with colorful databases and other technologies withoutre-implementation. It effectively saves a lot of energy, time and plutocrat.

Scope of php

PHP has two kinds of scopes for variables. There is a general global compass, where variables you define in the program are available in all places, like circles and other lines which include the train with variables. also there’s a original compass for stoner- defined functions, in which the variables are confined to that particular function.

Basic PHP Syntax

A PHP script starts with :

<?php
// PHP code goes here
?>

Echo
$color

PHP variables and constants

PHP Constants are variables whose values, formerly defined, can not be changed, and these constants are defined without a$ subscribe in the morning. PHP Constants are created using define() function. This function takes two parameters first is the name, and second is the value of the constant defined.

Types of data in php

Variables can store data of different types, and different data types can do different effects.
PHP supports. the following data types

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

Expressions

Expressions are the most important structure blocks of PHP. In PHP, nearly anything you write is an expression. The simplest yet most accurate way to define an expression is” anything that has a value”.

Scopes of a variable

The compass of a variable refers to its availability and visibility within different corridor of the law. PHP has two main reaches for variables original and global.

Local

Variables declared inside a function or method have a local scope. They are only accessible within that specific function or method. Local variables are not accessible outside the function or method in which they are defined. Once the function or method execution is complete, the local variables are destroyed and their values are no longer available.

Global

Variables declared outside of any function or method have a global scope. They are accessible from anywhere within the PHP script, including inside functions or methods. Global variables can be used and modified in different parts of the code.

PHP Operators

operators are symbols or keywords used to perform various operations on variables and values. PHP supports a wide range of operators, which can be classified into several categories. Here are the main categories of operators in PHP:

  1. Arithmetic Operators
    • Addition: +
    • Subtraction: –
    • Multiplication: *
    • Division: /
    • Modulus: %
    • Increment: ++
    • Decrement: —
  2. Assignment Operators:
    • Assignment: =
    • Addition assignment: +=
    • Subtraction assignment: -=
    • Multiplication assignment: *=
    • Division assignment: /=
    • Modulus assignment: %=
  3. Comparison Operators:
    • Equal to: ==
    • Identical to: ===
    • Not equal to: !=
    • Not identical to: !==
    • Greater than: >
    • Less than: <
    • Greater than or equal to: >=
    • Less than or equal to: <=
  4. Logical Operators:
    • And: && or and
    • Or: || or or
    • Not: ! or not
    • Exclusive Or: xor
  5. Bitwise Operators:
    • AND.
    • OR.
    • XOR.
    • NOT.
    • Left Shift.
    • Right Shift.
  6. Ternary Operator:
    • The ternary operator, also known as the conditional operator, is a concise way to write if-else statements. It takes three operands and returns the value of the second or third operand based on a condition.
    • The syntax for the ternary operator is: (condition) ? expression1 : expression2.
    • If the condition evaluates to true, expression1 is executed; otherwise, expression2 is executed.
  7. Modulus (MOD) Operator:
    • The modulus operator, represented by the percent sign (%), returns the remainder when one number is divided by another.
    • It is often used to perform operations related to divisibility or to cycle through a set of values.

PHP operator Precedence

The POP actually specifies how two expressions are tightly bound together and estimate first. Operator Precedence is also decided when and how the drivers are grouped using different gap types. Operator Precedence can be advanced priority or lower priority or equal priority.

Handling HTML form with PHP

To handle an HTML form with PHP, you need to perform the following steps:

Create the HTML form

Start by creating an HTML form in your web page. The form should have the action attribute set to the PHP file that will handle the form submission.

Create the PHP file to handle the form submission

In this step, create a PHP file (in this case, process.php) that will receive the form data and perform any necessary processing or validation.

Submitting the form

When the user submits the form by clicking the “Submit” button, the form data will be sent to the process.php file. The PHP code in process.php will handle the data and perform the necessary actions.

Capture Form Data

To capture form data in PHP, you can use the $_POST or $_GET superglobals, depending on the form submission method. Here’s an example of capturing form data using the $_POST superglobal:

  1. Create an HTML form in your PHP file (form.html):
  2. Create a PHP file (process_form.php) to process the submitted form data:

GET method

The GET system is used to submit the HTML form data. This data is collected by the predefined$, GET variable for processing.

The information transferred from an HTML form using the GET system is visible to everyone in the cybersurfer’s address bar, which means that all the variable names and their values will be displayed in the URL. thus, the progeny system isn’t secured to shoot sensitive information.

POST method

Analogous to the GET system, the POST system is also used to submit the HTML form data. But the data submitted by this system is collected by the predefined superglobal variable$, POST rather of$, GET.

Unlike the GET system, it doesn’t have a limit on the quantum of information to be transferred. The information transferred from an HTML form using the POST system isn’t visible to anyone.

Dealing with multi value fields

dealing with multi-value fields such as checkboxes or select multiple inputs, you need to handle the submitted values appropriately. Here are a few steps you can follow to handle multi-value fields in PHP:

  1. HTML Form
  2. PHP Processing

Form Redirect

you can redirect a form after submission using the header() function, which sends a raw HTTP header to the browser.

PHP conditional events and Loops

If-Else Conditional Statements (Nested If and Else)

The if- additional statement allows you to execute different blocks of law grounded on a condition. Then is an illustration of nested if- additional statements:

if (condition1) {
    // Code to execute if condition1 is true
} elseif (condition2) {
    // Code to execute if condition1 is false and condition2 is true
} else {
    // Code to execute if both condition1 and condition2 are false
}

Switch Case

The switch case statement provides an alternative way to handle multiple conditions. It evaluates an expression and executes the code block that matches the expression value. Here’s an example:

switch ($variable) {
    case value1:
        // Code to execute if $variable matches value1
        break;
    case value2:
        // Code to execute if $variable matches value2
        break;
    default:
        // Code to execute if $variable doesn't match any cases
        break;
}

While Loop

The while loop allows you to repeat a block of code as long as a condition is true. Here’s an example:

while (condition) {
    // Code to execute while the condition is true
    // Make sure to include a way to update the condition; otherwise, it may result in an infinite loop
}

For Loop

The for circle provides a compact way to reiterate over a range of values. It consists of three corridor initialization, condition, and replication. Then is an illustration :

for ($i = 0; $i < 5; $i++) {
    // Code to execute for each iteration of the loop
}

Do-While Loop

The do-while loop is similar to the while loop but executes the code block at least once before checking the condition. Here’s an example:

do {
    // Code to execute at least once
    // Make sure to include a way to update the condition
} while (condition);

Goto

The goto statement allows you to transfer control to a specific part of your code. However, it is generally recommended to avoid using goto as it can make the code harder to read and maintain.

Break

break is used to terminate the current loop and resume execution at the next statement after the loop.

Continue

continue is used to skip the rest of the current iteration and move to the next iteration of the loop.

Exit

exit is used to terminate the script execution entirely.

PHP Functions

PHP function is a piece of law that can be reused numerous times. It can take input as argument list and return value. There are thousands of erected- in functions in PHP.

In PHP, we can define tentative function, Function within Function and Recursive function also.

Benefits & Usage

Functions in PHP programming serve several important purposes:

  1. Code organization.
  2. Reusability.
  3. Modularity.
  4. Abstraction.
  5. Parameterization.
  6. Code readability and maintainability.

Declaration

A function protestation is demanded when the process of defining a function takes place in one source train. also, it’s possible to call that function in another train. In such a situation, one must declare the function at the top of the train calling the function.

Calling of a function

PHP, like utmost other programming languages has a small set of inbuilt drivers for operations with figures, strings and some other types of data( we’ll bandy them latterly). The number of drivers in PHP is limited and can not be extended. On the other hand, inventors always face situations when having other drivers would be useful.

PHP Function with Arguments

In PHP programming, you can produce a function with arguments by defining the function and specifying the arguments within the hiatuses. Then is an illustration of a PHP function with arguments

function greet($name) {
    echo "Hello, $name!";
}

// Call the function and pass an argument
greet("John");

Default Argument Values Function

PHP allows you to define C style dereliction argument values. In similar case, if you do not pass any value to the function, it’ll use dereliction argument value.

Let’ see the simple illustration of using PHP dereliction arguments in function.

<?php  
function sayHello($name="Ram"){  
echo "Hello $name<br/>";  
}  
sayHello("Sonoo");  
sayHello();//passing no value  
sayHello("Vimal");  
?>  

function with arguments

A function is defined with two formal arguments. When this function is called by passing the arguments by value. Arguments of function come its original variables.

Hence, any change in value of argument inside a function does not reflect outside it. Then, value of$ x is changed inside the function, but if we check its value after call to serve, it has not changed

Function call by value

Still, we generally shoot arguments when the function is called, If any PHP function acceptsparameters.However, it’s known as function call by value, If we shoot values as arguments when function is called. With function call by value fashion, the value of a variable that’s transferred as argument keeps unchanged although it’s altered in function body.

We generally use function call value fashion utmost of our PHP programs. The following law is an illustration of function call by value in PHP.

<?php
function addTen($num){
  $num=$num+10;
  print("Inside function:".$num);
}
$num=10;
addTen($num);
print("Outside function:".$num);
?>

Call By Reference

In case of PHP call by reference, factual value is modified if it’s modified inside the function. In similar case, you need to use &( ampersand) symbol with formal arguments. The & represents reference of the variable.

Global Scope

Variables or functions declared in the global scope are accessible from anywhere within the PHP script, including inside functions, classes, and other code blocks. They are defined outside of any function or class.

Local Scope

Variables or functions declared within a specific code block, such as inside a function or a loop, have local scope. They are only accessible within that particular code block and are not visible outside of it.

String Manipulation

strlen() This is used to find the length of the string. It gives affair how multitudinous characters do the string has() To find the number of words in a string. It gives number of words that the given string contains.() To reverse a string. It gives affair as the reverse of that string. If the string contains further than one word the words will be arranged in hinder order else the letter of the words get reversed. strpos() To search for a specific string. It searches for a specific string in the string and returns the fist index of the string if it’s set up fresh- 1.() Replace text with in a string.

Regular Expression

Regular expressions are generally known as regex. These are nothing further than a pattern or a sequence of characters, which describe a special hunt pattern as textbook string. Regular expression allows to search a specific string inside another string. Indeed we can replace one string by another string and also resolve a string into multiple gobbets. They use computation drivers(,-,) to produce complex expressions.

Searching string

To search for a string in a PHP program, you can use colorful string functions and ways. Then is an illustration of how you can perform a introductory hunt using the strpos() function:

<?php
$string = "This is a sample string";
$needle = "sample";

$position = strpos($string, $needle);

if ($position === false) {
    echo "String not found.";
} else {
    echo "String found at position: " . $position;
}
?>

Replacing String

To replace a string in PHP programming, you can use the str_replace() function. It replaces all occurrences of a specified string with another string within a given string.

The syntax for str_replace() is as follows:

str_replace($search, $replace, $subject, $count);

Formatting,

Formatting in PHP programming refers to the practice of organizing and styling your code to make it more readable, maintainable, and easier to understand. Proper formatting can improve code clarity, reduce errors, and make collaboration with other developers smoother.

Joining Strings

To concatenate or join multiple strings together, you can use the concatenation operator (.) or the implode() function.

  1. Using the concatenation operator.
  2. Using the implode() function.

Splitting Strings

To split a string into an array of substrings based on a specific delimiter or pattern, you can use functions such as explode() or preg_split().

  1. Using the explode() function.
  2. Using the preg_split() function.

String Library functions

To split a string into an array of substrings based on a specific delimiter or pattern, you can use functions such as explode() or preg_split().

  1. strlen(str).
  2. strcpy(dest, src).
  3. strcat(dest, src).
  4. strcmp(str1, str2).
  5. strchr(str, c).
  6. strstr(str1, str2).
  7. toupper(c).
  8. tolower(c).
  9. sprintf(dest, format, …).
  10. strtok(str, delim)

Use of preg_match()

The preg_match() function takes two main arguments: the regular expression pattern and the string to be matched. It returns 1 if the pattern matches, 0 if it doesn’t match, or false if an error occurs.

Here’s the general syntax of preg_match():

preg_match($pattern, $string, $matches);

preg_replace()

preg_replace() is a function in PHP used for performing regular expression pattern matching and replacing. It allows you to search and replace textbook grounded on a pattern defined using regular expressions.

The syntax of thepreg_replace() function is as follows

preg_replace($pattern, $replacement, $subject, $limit = -1, &$count)

preg_split() functions

The preg_split() function in PHP is used to split a string into an array of substrings based on a specified regular expression pattern. It allows you to break a string into smaller parts based on certain criteria defined by the regular expression.

The basic syntax of preg_split() is as follows:

preg_split(pattern, subject, limit = -1, flags = 0)

Array

An array in PHP is actually an ordered chart. A chart is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list( vector), hash table( an perpetration of a chart), wordbook, collection, mound, line, and presumably more.

Anatomy of an Array

An array is a data structure that can store multiple values of different types in a single variable. It allows you to organize and manipulate collections of data efficiently. Here’s an overview of the anatomy of an array in PHP:

  1. Anatomy of an Array
  2. Indexing
  3. Array Length
  4. Adding Elements
  5. Associative Arrays
  6. Multidimensional Arrays
  7. Array Functions

Index-based array

you can create an indexed array by simply declaring a variable and assigning an array of values to it. Here’s an example:

$myArray = array("apple", "banana", "orange", "grape");

In the above code, $myArray is an indexed array that contains four elements: “apple” at index 0, “banana” at index 1, “orange” at index 2, and “grape” at index 3.

You can also use the square bracket syntax to create an indexed array:

$myArray = ["apple", "banana", "orange", "grape"];

Associatve array

An associative array is a data structure that allows you to associate keys with values. Unlike a regular, indexed array, where the keys are numeric and automatically assigned, an associative array uses custom keys that you define.

Looping with Index Arr

you can loop through an indexed array using various looping constructs such as for, foreach, and while. Here are examples of how you can loop through an indexed array using each of these constructs:

  1. Using a for loop
  2. Using a foreach loop
  3. Using a while loop with an incrementing index

Associative array

PHP allows you to associate name/ marker with each array rudiments in PHP using = > symbol. similar way, you can fluently flash back the element because each element is represented by marker than an incremented number.