PHP NOTES
PHP NOTES
Introudction To PHP
PHP is the most popular scripting language on the web
PHP is a server side scripting language that is embedded in HTML. It is used to manage dynamic content, databases, session tracking, even build entire e-commerce sites.
stand for ‘Personal Home Page’. But, now, PHP is known as Hypertext Preprocessor
It works for server-side development It is an object-oriented open-source scripting language.
It is possible to embed PHP into HTML
Advantages of PHP/PHP Features
To understand PHP, it is vital to address its features. There are multiple notable ones available:
Cross-platform– PHP can efficiently work on different operating systems, like Linux, Windows, and Mac.
Simple – Another benefit of this language is that even beginners can quickly adapt to PHP programming. It is one of the more accessible languages to pick up.
Open-source– Anyone can use PHP for their web development requirements since the original code has an open-source nature. Anyone can adapt it and build upon the code further.
High-quality performance– PHP operates faster than other scripts like ASP and JSP since it uses a personalized memory. Therefore, the loading time and workload are relatively shorter.
High-security– Among the different scripting language types available, PHP is one of the most secure options with multiple security levels in place. The multi-layered structure safeguards against hacking attempts, malware, etc. Web
Embed PHP code in an HTML page
PHP is the abbreviation of Hypertext Preprocessor and earlier it was abbreviated as Personal Home Page.
We can use PHP in HTML code by simply adding a PHP tag without doing any extra work.
you can directly applying php code in html page this techniques is one of the main advantage of php language embedding PHP code in HTML page
To embed PHP code in HTML pages we define to outline blocks of PHP code so save the page with the special extension (.php).
<?php
echo "Hello World"; // PHP Code
?>
<html>
<title>First Application of PHP</title>
<body>
<h3>Here Embed PHP code!</h3>
<?php
echo "hello World"; // inserted php code in HTML
?>
</body>
</html>
Wrighting comment in PHP
In PHP, comments are sections of code that are not executed when a program is run.
End users do not see PHP comments — they are only visible when viewing the PHP code in a file. PHP comments are usually meant to help programmers understand
A PHP comment can explain the purpose of a particular section of code to other programmers. This way, when a developer is viewing a PHP file for the first time, they can more easily understand the code they’re looking at.
PHP has two built-in ways of commenting:
1. single-line comments
2. multiline comments.
Single line comments :
To leave a single-line comment, type two forward slashes (//) followed by your comment text.
All text to the right of the // will be ignored.
You can also use a hash symbol (#) instead of // to make a single-line comment.
Syntax :
// This is comment
Multiline comments :
PHP also allows for comments that span multiple lines, in case you want to comment out a
larger section of code or leave a more descriptive comment.
Start your multiline comment by writing /* and end it by writing */. For example: Syntax
/*
This is inside comment
*/.
Data Types :
Variables can store data of different types, and different data types can do different things.
PHP supports the following data types:
• String Data type
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:
Syntax :
$x = "Hello world!"; // This is string
$y = 'Hello world!';
Example
<?php
$x = "Hello world!";
$y = 'Hello world!';
echo $x;
echo "<br>";
echo $y;
?>
PHP Integer
Integers are whole numbers, without a decimal point (..., -2, -1, 0, 1, 2, ...).
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
$x = 5985; // This is integer value
Example
<?php
$x = 5985;
var_dump($x);
?>
Var_dump () returns data type of variable
PHP 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; // This is float value
var_dump($x);
?>
PHP Boolean
A Boolean represents two possible states: TRUE or FALSE.
Boolean data types are used in conditional testing. Hold only two values, either TRUE(1) or FALSE(0).
Boolean represents a truth value that can be either true or false. PHP uses the bool keyword to represent the Boolean type.
Syntax :
$x = true;
$y = false;
PHP Keywords
PHP has a set of keywords that are reserved words which cannot be used as function names, class names or method names. Prior to PHP 7, these keywords could not be used as class property names either:
there are various words, letters, and digits. Every word used in a PHP program is classified either as a Keyword or an Identifier
Following are the list of keyword :
Keyword |
Description
|
abstract |
Declare a class as abstract |
and |
A logical operator |
as |
Used in the foreach loop |
break |
Break out of loops and switch statements |
callable |
A data type which can be executed as a function |
case |
Used in the switch conditional |
catch |
Used in the try..catch statement |
Variables
Variables in a program are used to store some values or data that can be used later in a program. The variables are also like containers that store character values, numeric values, memory addresses, and strings. PHP has its own way of declaring and storing variables.
Any variables declared in PHP must begin with a dollar sign ($),
• A variable name can only contain alphanumeric( char+ num) characters
• and underscores (i.e., ‘a-z’, ‘A-Z’, ‘0-9, and ‘_’) in their name.
• it cannot start with a number.
Example :
<?php
$txt = "Hello world!"; //String variable
$x = 5; // int variable
$y = 10.5; // Float variable
?>
Local variables:
The variables declared within a function are called local variables to that function and have their scope only in that particular function. In simple words, it cannot be accessed outside that function. Any declaration of a variable outside the function with the same name as that of the one within the function is a completely different variable. We will learn about functions in detail in later articles. For now, consider a function as a block of statements.
function local_var()
{
// This $num is local to this function
$num = 50;
echo "local num = $num \n";
}
Global variables:
The variables declared outside a function are called global variables. These variables can be accessed directly outside a function. To get access within a function we need to use the “global” keyword before the variable to refer to the global variable
function global_var()
{
// we have to use global keyword before
global $num;
echo "Variable num inside function : $num \n";
}
The static Variable
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:
Constants
Constants are either identifiers or simple names that can be assigned any fixed values. They are similar to a variable except that they can never be changed. They remain constant throughout the program and cannot be altered during execution. Once a constant is defined, it cannot be undefined or redefined. Constant identifiers should be written in upper case following the convention. By default, a constant is always case-sensitive
Creating a PHP Constant
The define() function in PHP is used to create a constant as shown below:
Syntax:
define(name, value, case_insensitive)
example
<?php
define('WIDTH','1140px'); // WIDHT is Constant
echo WIDTH;
?>
Expression and Operator in PHP
Almost everything in a PHP script is an expression. Anything that has a value is an expression. In a typical assignment statement ($x=100), a literal value, a function or operands processed by operators is an expression, anything that appears to the right of assignment operator (=)PHP divides the operators in the following groups:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Increment/Decrement operators
• Logical operators
• String operators
• Conditional assignment operators
Arithmetic Operators:
• The arithmetic operators are used to perform simple mathematical operations like addition, subtraction, multiplication, etc. Below is the list of arithmetic operators along with their syntax and operations in PHP.
Operator |
Name |
Syntax |
Operation |
+ |
Addition |
$x + $y |
Sum the operands |
– |
Subtraction |
$x – $y |
Differences the operands |
* |
Multiplication |
$x * $y |
Product of the operands |
/ |
Division |
$x / $y |
The quotient of the operands |
<?php
$x = 29; // Variable 1
$y = 4; // Variable 2
echo ($x + $y), "\n";
echo($x - $y), "\n";
echo($x * $y), "\n";
echo($x / $y), "\n";
echo($x % $y), "\n";
?>
Assignment Operators: These operators are used to assign values to different variables, with or without mid-operations. Here are the assignment operators along with their syntax and operations, that PHP provides for the operations.
Operator |
Name |
Syntax |
= |
Assign |
$x = $y |
+= |
Add then Assign |
$x += $y |
-= |
Subtract then Assign |
$x -= $y |
*= |
Multiply then Assign |
$x *= $y |
Comparison Operators: These operators are used to compare two elements and outputs the result in boolean form. Here are the comparison operators along with their syntax and operations in PHP.
< |
Less Than |
$x < $y |
Returns True if $x is less than $y |
> |
Greater Than |
$x > $y |
Returns True if $x is greater than $y |
<= |
Less Than or Equal To |
$x <= $y |
Returns True if $x is less than or equal to $y |
>= |
Greater Than or Equal To |
$x >= $y |
Returns True if $x is greater than or equal to $y |
== |
Equal To |
$x == $y |
Returns True if both the operands are equal |
<?php
$a = 80;
$b = 50;
$c = "80";
var_dump($a == $c) + "\n";
var_dump($a < $b) + "\n";
var_dump($a > $b) + "\n";
?>
Increment/Decrement Operators:
These are called the unary operators as they work on single operands. These are used to increment or decrement values.
Operator |
Name |
Syntax |
Operation |
++ |
Pre-Increment |
++$x |
First increments $x by one, then return $x |
— |
Pre-Decrement |
–$x |
First decrements $x by one, then return $x |
++ |
Post-Increment |
$x++ |
First returns $x, then increment it by one |
— |
Post-Decrement |
$x– |
First returns $x, then decrement it by one |
<?php
$x = 2;
echo ++$x, " First increments then prints \n";
echo $x, "\n";
$x = 2;
echo $x++, " First prints then increments \n";
echo $x, "\n";
?>
String Operators: This operator is used for the concatenation of 2 or more strings using the concatenation operator (‘.’). We can also use the concatenating assignment operator (‘.=’) to append the argument on the right side to the argument on the left side.
Operator |
Name |
Syntax |
Operation |
. |
Concatenation |
$x.$y |
Concatenated $x and $y |
.= |
Concatenation and assignment |
$x.=$y |
First concatenates then assigns, same as $x = $x.$y |
PHP Conditional Statements
PHP also allows you to write code that perform different actions based on the results of a logical or comparative test conditions at run time
If Statement
The if statement is used to execute a block of code only if the specified condition evaluates to true. This is the simplest PHP's conditional statements and can be written like:
When we wish to execute a specific piece of code only when a condition is met, we use the conditional if statement
The code within the conditional statement will only be executed if the condition evaluates to true. When the condition is not true, the code within the conditional statement is ignored and processing continues after the close of the conditional statement.
Syntax
if(condition)
{
// Code to be executed
}
Example
<?php
$num=12;
if($num<100){
echo "$num is less than 100";
}
?>
if...else Statement
You can enhance the decision making process by providing an alternative choice through adding an else statement to the if statement. The if...else statement allows you to execute one block of code if the specified condition is evaluates to true and another block of code if it is evaluates to false. It can be written, like this:
Syntax :
if(condition)
{
// Code to be executed if condition is true
}
Else
{
// Code to be executed if condition is false
}
Example:
<?php
$num=12;
if($num%2==0)
{
echo "$num is even number";
}else{
echo "$num is odd number";
}
?>
PHP Switch
PHP switch statement is used to execute one statement from multiple conditions. It works like PHP if-else-if statement
The switch statement is used to perform different actions based on different conditions.
switch(expression)
{
case value1:
//code to be executed
break;
case value2:
//code to be executed
break;
......
default:
code to be executed if all cases are not matched;
}
The default is an optional statement. Even it is not important, that default must always be the last statement. Each case can have a break statement, which is used to terminate the sequence of statement.
Program
<?php
$num=20;
switch($num){
case 10:
echo("number is equals to 10");
break;
case 20:
echo("number is equal to 20");
break;
case 30:
echo("number is equal to 30");
break;
default:
echo("number is not equal to 10, 20 or 30");
}
?>
The ternary operator (?:)
is a conditional operator used to perform a simple comparison or check on a condition having simple statements. It decreases the length of the code performing conditional operations. The order of operation of this operator is from left to right. It is called a ternary operator because it takes three operands- a condition, a result statement for true, and a result statement for false.
This is treated as an alternative method of implementing if-else or even nested if-else statements.
Syntax:
(Condition) ? (Statement1) : (Statement2);
• Condition: It is the expression to be evaluated and returns a boolean value.
• • Statement 1: It is the statement to be executed if the condition results in a true state.
• • Statement 2: It is the statement to be executed if the condition results in a false state.
Example:
<?php
$a = 10;
$b = $a > 15 ? 20 : 5;
print ("Value of b is " . $b); ?>
Output:
Value of b is 5
An advantage of using a ternary operator is that it reduces the huge if-else block to a single line, improving the code readability and simplify it.
Looping Statement in php:
Often when you write code, you want the same block of code to run over and over again a certain number of times. So, instead of adding several almost equal code-lines in a script, we can use loops.
Loops are used to execute the same block of code again and again, as long as a certain condition is true.
PHP supports four types of looping techniques;
1. for loop
2. while loop
3. do-while loop
for loop:
This type of loops is used when the user knows in advance, how many times the block needs to execute. That is, the number of iterations is known beforehand. These type of loops are also known as entry-controlled loops. There are three main parameters to the code, namely the initialization, the test condition and the counter.
Syntax:
for (initialization expression; test condition; update expression)
{
// code to be executed
}
Example
<?php
// code to illustrate for loop
for ($num = 1; $num <= 10; $num += 2) {
echo "$num \n";
}
?>
while loop:
The while loop is also an entry control loop like for loops i.e., it first checks the condition at the start of the loop and if its true then it enters the loop and executes the block of statements, and goes on executing it as long as the condition holds true.
Syntax:
while (if the condition is true)
{
// code is executed
}
<?php
$num = 2;
while ($num < 12) {
$num += 2;
echo $num, "\n";
}
?>
The while statement will execute a block of code if and as long as a test expression is true.
do-while loop:
This is an exit control loop which means that it first enters the loop, executes the statements, and then checks the condition. Therefore, a statement is executed at least once on using the do…while loop. After executing once, the program is executed as long as the condition holds true.
The do...while statement will execute a block of code at least once - it then will repeat the loop as long as a condition is true.
Syntax:
do {
//code is executed
} while (if condition is true);
<?php
$num = 2;
do {
$num += 2;
echo $num, "\n";
} while ($num < 12);
?>
What is PHP Arrays
An array is a special variable that we use to store or hold more than one value in a single variable without having to create more variables to store those values.
To create an array in PHP, we use the array function array( ).
By default, an array of any variable starts with the 0 index. So whenever you want to call the first value of an array you start with 0 then the next is 1...and so on.
Example:
<?php
$cars = array("Volvo", "BMW", "Toyota"); //cars is array
echo count($cars); // print 3
?>
There are different types of arrays in PHP. They are:
• • Indexed Arrays
• • Associative Arrays
• • Multidimensional Arrays
Indexed Array (Creating indexed array)
A numerical array is a type of array which can store strings, numbers, and objects
The index can be assigned automatically (index always starts at 0), like this:
Example
$cars = array("Volvo", "BMW", "Toyota");
OR
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
Associative Arrays :
In an associative array, the keys assigned to values can be arbitrary and user defined strings
An associative array is a type of array where the key has its own value. In an associative array, we make use of key and value
• When you want to store the age of different students along with their names.
• When you want to store the score of a student in different subjects
Then use associative array
Suppose we want to assign ages to a group of high school students with their names.
Example:
<?php
$student_age = array (
'Ram' => 17,
'Shital' => 18,
'Mahesh' => 16,
'Meera' => 17,
);
echo $student_age ['Ram'];
echo $student_age ['Shital'];
echo $student_age ['Meera'];
?>
What are Multidimensional Arrays?
You can think of a multidimensional array as an array of arrays. This means that every element in the array holds a sub-array within it. In general, multidimensional arrays allow you to store multiple arrays in a single variable.
A two-dimensional array is an array of arrays (a three-dimensional array is an array of 3).
Example
Name |
Stock |
Sold |
Volvo |
22 |
18 |
BMW |
15 |
13 |
Jeep |
5 |
2 |
Toyoto |
17 |
15 |
$cars is array
$cars = array (
array("Volvo",22,18), // 1 array for volvo car
array("BMW",15,13), // 2 array for BMW CAR
array("Jeep",5,2), // 3 array for jeep
array("Toyoto",17,15) // 4 array for toyoto CAR
);
Now the two-dimensional $cars array contains four arrays, and it has two indices: row and column
Accessing Array Elements
You can pick the value of an array element by accessing it. The accessed element value can be stored in a variable and used for a calculation. Array element can be accessed by index or key.
The syntax for accessing an array element in PHP is
$var-Name = Array-Name [index ]
Using Element Index
$StuMarks = array(45, 67,34,42,77,21); // Array Name : StuMarks
Eg
$StuMarks[3]; // $marks variable will get value stored at index 3 in
$StuMarks array
Using String Keys
$StuMarks=array (“Sam”=>45, “Rob”=>67,”May”=>34,”Han”=>42,”Jon”=>77,”Pam”=>21);
In this example the elements values and keys are assigned in this way
Displaying Array : For ..each()
There is always a need to iterate through each element of the array. You have already learned about looping constructs in PHP that can be used to iterate through array elements
This loop is used only for arrays. The value of the current array element will be assigned to a variable for each pass, and the array pointer will be moved by one FOREACH loop iteration. This process will be continued until it will reach the last array element.
<html> <body>
<?php
$a=array("Red","Green","Blue","Yellow");
foreach($a as $t) // For each loop
{
echo $t."<br>";
}
?>
</body>
</html>
In this program, an array $a is containing four elements. For each loop iteration, here the value of current array element is assigning to the variable $t, an array pointer is moving by one and displaying the value of each array element until the last array element is found.
Using array functions
PHP Array Functions
PHP provides various array functions to access and manipulate the elements of array. The important PHP array functions are given below.
array() function
PHP array() function creates and returns an array. It allows you to create indexed, associative and multidimensional arrays.
Syntax
1. array array ([ mixed $... ] )
<?php
$season=array("summer","winter","spring","autumn");
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>
array_change_key_case() function
PHP array_change_key_case() function changes the case of all key of an array.
Note: It changes case of key only.
Syntax
array_change_key_case ( array $array [, int $case = CASE_LOWER ] )
Example
<?php
$salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
print_r(array_change_key_case($salary,CASE_UPPER));
?>
Out put
array_chunk() function
PHP array_chunk() function splits array into chunks. By using array_chunk() method, you can divide array into many parts. Syntax
array array_chunk ( array $array , int $size [, bool $preserve_keys = false ] )
Example
<?php
$salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
print_r(array_chunk($salary,2));
?>
count() function
PHP count() function counts all elements in an array.
int count ( $array)
<?php
$season=array("summer","winter","spring","autumn");
echo count($season);
?>
PHP sort() function
PHP sort() function sorts all the elements in an array.
Syntax
<?php
$season = array ("summer","winter","spring","autumn");
sort($season); -----------→ sort the array
foreach( $season as $s )
{
echo "$s<br />";
}
?>
array_reverse() function
PHP array_reverse() function returns an array containing elements in reversed order.
<?php
$season = array("summer","winter","spring","autumn");
$reverseseason = array_reverse($season);
foreach( $reverseseason as $s )
{
echo "$s<br />";
}
?>
Output:
autumn
spring
winter
array_search() function
PHP array_search() function searches the specified value in an array. It returns key if search is successful.
<?php
$season=array("summer","winter","spring","autumn");
$key=array_search("spring",$season);
echo $key;
?>
Output: 2
include() Function
The Include() function is used to put data of one PHP file into another PHP file. If errors occur then the include() function produces a warning but does not stop the execution of the script i.e. the script will continue to execute.
Syntax
include("path/to/filename")
statement allow you to include the code contained in a PHP file within another PHP file. Including a file produces the same result as copying the script from the file specified and pasted into the location where it is called.
<html>
<body bgcolor="pink">
<?php include("abc.php"); ?>
<h2><b>Welcome Tutorials</b></h2>
<p>This page created abc.</p>
</body>
</html>
Require() Function
The Require() function is also used to put data of one PHP file to another PHP file. If there are any errors then the require() function produces a warning and a fatal error and stops the execution of the script i.e. the script will continue to execute.
Syntax
require("path/to/filename");
example
<html lang="en">
<head>
<title>Tutorial Republic</title>
</head>
<body>
<?php include "header.php"; ?>
<?php include "menu.php"; ?>
<h1>Welcome to Our Website!</h1>
<p>Here you will find lots of useful information.</p>
<?php include "footer.php"; ?>
</body> </html>
Difference Between include and require Statements
The only difference is — the include() statement will only generate a PHP warning but allow script execution to continue if the file to be included can't be found, whereas the require() statement will generate a fatal error and stops the script execution.
Functions in PHP
A function is a block of code written in a program to perform some specific task
PHP function is a piece of code that can be reused many times. It can take input as argument list and return value. There are thousands of built-in functions in PHP.
A function will be executed by a call to the function. A function will not execute automatically when a page loads.
PHP provides us with huge collection of built-in functions.(already defined) These functions are already coded and stored in form of functions.
PHP allows us to create our own customised functions called the user-defined functions.
writeMsg(); // call the function
Defining and calling a Function :
The declaration of a user-defined function start with the word function, followed by the name of the function you want to create followed by parentheses i.e. () and finally place your function's code between curly brackets {}
Syntax :
function functionName()
{
// Code to be executed
}
Example :
<?php
function sayHello()
{
echo "Hello PHP Function";
}
sayHello();//calling function
?>
We can pass the information in PHP function through arguments which is separated by comma.
PHP supports Call by Value (default), Call by Reference, Default argument values
<?php
function sayHello($name) --------→ contains argrument
{
echo "Hello $name<br/>";
}
sayHello("Sonoo");
sayHello("Vimal");
sayHello("John");
?>
Calling Function :
To call defined function we can use simply name of php as
functionName(); ---------→ calling function
in above example
Sayhello(“Vimal”); ---------→ call function with name SayHello()
Returning Values from a Function
Functions can also return values to the part of program from where it is called. The return keyword is used to return value back to the part of program, from where it was called. The returning value may be of any type including the arrays and objects. The return statement also marks the end of the function and stops the execution after that and returns the value.
<?php
function getSum($num1, $num2){
$total = $num1 + $num2;
return $total;
}
echo getSum(5, 10); // Outputs: 15
?>
Date and Time
Date and time are some of the most frequently used operations in PHP while executing SQL queries or designing a website etc. PHP serves us with predefined functions for these tasks. Some of the predefined functions in PHP for date and time
PHP date function is an in-built function that simplify working with date data types. The PHP date function is used to format a date or time into a human readable format
date() Function: The PHP date() function converts timestamp to a more readable date and time format.
• “date(…)” is the function that returns the current timestamp in PHP on the server.
• • “format” is the general format which we want our output to be i.e.;
• • “Y-m-d” for PHP date format YYYY-MM-DD
• • “Y” to display the current year
Syntax :
<?php
date(format,[timestamp]);
?>
<?php
echo date("Y");
?>
<?php
echo "Today's date is :";
$today = date("d/m/Y");
echo $today;
?>
Output:
Today's date is :05/12/2017
<?php
echo "Today's date in various formats:" . "\n";
echo date("d/m/Y") . "\n";
echo date("d-m-Y") . "\n";
echo date("d.m.Y") . "\n";
echo date("d.M.Y/D");
?>
Today's date in various formats:
05/12/2017
05-12-2017
05.12.2017
05.Dec.2017/Tue
PHP time() Function:
The time() function is used to get the current time as a Unix timestamp (the number of seconds since the beginning
A timestamp in PHP is a numeric value in seconds between the current time and value as at 1st January, 1970 00:00:00
Working with date and time functions is very common in PHP. Date and time functions help you to get the current date and time from the server and also enables you to format the date and time in a proper manner etc
<?php
$timestamp = time();
echo($timestamp);
echo "\n";
echo(date("F d, Y h:i:s A", $timestamp));
?>
PHP String Functions
a string is considered a data type, which in general is a sequence of multiple characters that can contain whitespaces, numbers, characters, and special symbols as well.
For example, “Hello World!”, “ID-34#90” etc.
PHP also allows single quotes(‘ ‘) for defining a string.
Every programming language provides some in-built functions for the manipulation of strings. Some of the basic string functions provided by PHP are as follows
$my_string = 'Hello World';
strlen() Function: It returns the length of the string i.e. the count of all the
characters in the string including whitespaces characters
Syntax :
strlen(string or variable name);
<?php
$str = "Hello World!";
echo strlen($str);
// Prints 13 in a new line
echo "<br>" . strlen("GeeksForGeeks");
?>
strrev() Function: It returns the reversed string of the given string.
Syntax :
strrev(string or variable name)
<?php
$str = "Hello World!";
echo strrev($str);
?>
trim(), ltrim(), rtrim() Functions:
It remove white spaces or other characters from the string. They have two parameters: one string and another charList, which is a list of characters that need to be omitted.
• trim() – Removes characters or whitespaces from both sides
• rtrim() – Removes characters or whitespaces from right side.
• ltrim() – Removes characters or whitespaces from the left side.
<?php
$str = "\nThis is an example for string functions.\n";
// Prints original string
echo $str;
// Removes whitespaces from right end
echo chop($str) . "<br>";
// Removes whitespaces from both ends
echo trim($str) . "<br>";
// Removes whitespaces from right end
echo rtrim($str) . "<br>";
// Removes whitespaces from left end
echo ltrim($str);
?>
strtoupper() and strtolower() Function:
It returns the string after changing cases of its letters.
• • strtoupper() – It returns the string after converting all the letters to uppercase.
• • strtolower() – It returns the string after converting all the letters to lowercase.
<?php
$str = "Welcome";
echo strtoupper($str)."<br>";
echo strtolower($str);
?>
What is object : Class and Object
Object-Oriented Programming (OOP) is a programming model that is based on the concept of classes and objects.
in object-oriented programming the focus is on the creations of objects which contain both data and functions together.
PHP also supports object oriented programming
1. Classes are the blueprints of objects. One of the big differences between functions and classes is that a class contains both data (variables) and functions that form a package called an: ‘object’.
2. Class is a programmer-defined data type, which includes local methods and local variables.
3. Class is a collection of objects. Object has properties and behavior.
Class:
Each class contains the required variables and functions to define the properties of a particular group. Generally, the name of the class is defined by starting with the capital letter and in the singular form. The keyword, the class is used to declare a class.
A class is defined by using the class keyword, followed by the name of the class and a pair of curly braces ({}). All its properties and methods go inside the braces:
Syntax for class
<?php
class person {
}
?>
Example
<?php
class Fruit { ----------------→ Class fruit
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
?>
Object
An Object is an individual instance of the data structure defined by a class. We define a class once and then make many objects that belong to it. Objects are also known as instances.
The object is declared to use the properties of a class. The object variable is declared by using the new keyword followed by the class name. Multiple object variables can be declared for a class.
Syntax:
$object_name = new Class_name()
Creating an Object:
Following is an example of how to create object using new operator.
class Books {
// Members of class Books
}
// Creating three objects of Books
$physics = new Books; //object of book class
$maths = new Books; all are object of Books Class //object of book class
$chemistry = new Books; //object of book class
<?php
class Fruit {
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
$apple = new Fruit();
$banana = new Fruit();
$apple->set_name('Apple');
$banana->set_name('Banana');
echo $apple->get_name();
echo "<br>";
echo $banana->get_name();
?>
Overloading in PHP
What is function overloading? Function overloading is the ability to create multiple functions of the same name with different implementations. Function
overloading in PHP? Function overloading in PHP is used to dynamically create properties and methods.
Method Overloading is a concept of Object Oriented Programming which helps in building the composite application in an easy way.
• o All overloading methods must be defined as Public.
• o In simple words, “Overloading means declaring a function multiple times with a different set of parameters”. So, if you would like to explain this in terms of a simple example, it would look like so.
function foo($a)
{
return $a;
}
function foo($a, $b)
{
return $a + $b;
}
echo foo(5); // should print "5"
echo foo(5, 2); // Should prints "7"
Introduction on Object in PHP
Objects are real-world entities. Objects are defined from classes in Object-
Oriented Programming like PHP. When a class is defined, we can create many objects out of the class. Example Class Car is defined, then Mercedes, BMW, Skoda are all objects of the Class Car. A class is a blueprint of an object. A class contains variables and functions. These data variables are called properties and data functions are called data methods
The definition of an object goes like this, An object is an instance of a class. We can create an instance of the class by using the new keyword. We can create multiple instances of the class. These instances can now access the class functions, the class members
How to Create an Object?
Creating an object is the same as instantiating a class. This instance is created using the new keyword. This process is called instantiation. Since objects are instances of a class and can be created using a new keyword let us take a look at how these instances are created.
Syntax:
objectname = new Classname();
Examples:
$parrot = new Bird();
$pigeon = new Bird();
$woodpecker = new Bird();
Properties of Object
Properties are variables that are defined within a class. These variables are then used by the methods, objects of the class.
These variables can be public, protected or private. By default, the public is used. The value of a variable may or may not contain a default value, meaning that the variable may be initialized with a value or not.
The variable names are case sensitive, meaning that $name is different from $Name. There is a naming convention like if the variable contains more than one word than the second word will start with a capital letter like $firstName, $lastName and so on.
Let us look at the below program to understand the properties.
class Birds {
public $birdsFly = ‘sky’;
public $birdsSound = ‘vocal’;
public $birdsBuildNests =’trees’;
}
$birdsFly == is property
‘sky’ === is value
Program Class and object
<?php
class foo
{
function do_foo()
{
echo "Doing foo.";
}
}
$bar = new foo;
$bar->do_foo();
?>
Methods of Object in PHP
As the properties of a class, we can define member functions in a class. These functions can then be called from an object. These functions are called as methods of a class. These functions can be public, private or protected. By default is public. Also while declaring the function we declare it as
Syntax:
public function functionaname() {
//statements
}
<?php
//example to access methods of a class
class Birds {
// properties
public $birdsFly;
//method 1 - set Method1
public function set_birdFlies($input) {
$this->birdsFly = $input ;
}
//method 1 - get Method1
public function get_birdFlies() {
return $this->birdsFly;
}
}
//object of class is declared
$obj = new Birds();
$obj->set_birdFlies('Fly');
echo '<br> Bird Flies = '.$obj->get_birdFlies();
$obj->set_BirdBuildsNest('Trees');
echo '<br> Bird Builds Nest = '.$obj->get_BirdBuildsNest();
?>
PHP - What is Inheritance?
Inheritance in OOP = When a class derives from another class.
The child class will inherit all the public and protected properties and methods from the parent class. In addition, it can have its own properties and methods.
An inherited class is defined by using the extends keyword.
It is a concept of accessing the features of one class from another class. If we inherit the class features into another class, we can access both class properties. We can extends the features of a class by using 'extends' keyword.
Let's look at an example:
<?php
class a
{
function fun1()
{
echo "javatpoint";
}
}
class b extends a
{
function fun2()
{
echo "SSSIT";
}
}
$obj= new b();
$obj->fun1();
?>
What is MySQL?
MySQL is a relational database management system (RDBMS) developed by Oracle that is based on structured query language (SQL).
MySQL is open-source
Any individual or enterprise may freely use, modify, publish, and expand on Oracle’s open-source MySQL code base. The software is released under the GNU General Public License (GPL).
Though MySQL’s relational nature and the ensuing rigid storage structures might seem restrictive, the tabular MySQL is easy to use
paradigm is perhaps the most intuitive, and ultimately allows for greater usability.
Executing Simple Queries
Once you have successfully connected to and selected a database, you can start performing queries. These queries can be as basic as inserts, updates, and deletions or as involved as complex joins returning numerous rows. In any case, the PHP function for executing a query is
mysql_query():
$result = mysql_query($query);
For simple queries like INSERT, UPDATE, DELETE, etc. (which do not return records), the $result variable will be either TRUE or FALSE based upon the successful execution of the query on the database. For complex queries that do return records (SELECT, SHOW, DESCRIBE, and EXPLAIN),
Example
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); $mysqli = new mysqli("example.com", "user", "password", "database");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
Retrive Query Result
For retrieve data from MySQL the SELECT statement is used. We can retrieve data from specific column or all column of a table.
To retrieve selected column data from database the SQL query is
SELECT column_name,column_name FROM table_name;
To retrieve all the column data from a table the SQL query is
SELECT * FROM table_name;
Some of The Most Important SQL Commands
• SELECT - extracts data from a database
• UPDATE - updates data in a database
• DELETE - deletes data from a database
• INSERT INTO - inserts new data into a database
• CREATE DATABASE - creates a new database
• ALTER DATABASE - modifies a database
• CREATE TABLE - creates a new table
• ALTER TABLE - modifies a table
• DROP TABLE - deletes a table
• CREATE INDEX - creates an index (search key)
• DROP INDEX - deletes an index
Comments
Post a Comment