PHP (Hypertext Preprocessor /personal Home Page)
PHP (Hypertext Preprocessor /personal Home Page)
echo $txt;
echo "<br>";
echo $x;
echo "<br>";
echo $y;
?>
Output:
Hello world!
5
Local and Global Scope variables
<?php
$x=5; // global scope
myTest();
1. <?php
2. define("MESSAGE","Hello JavaTpoint PHP",true);//not case sensitive
3. echo MESSAGE, "</br>";
4. echo message;
5. ?>
1. <?php
2. define("MESSAGE","Hello JavaTpoint PHP",false);//case sensitive
3. echo MESSAGE;
4. echo message;
5. ?>
1.<?php
2.$x = "abc";
3.$$x = 200;
4.echo $x."<br/>";
5.echo $$x."<br/>";
6.echo $abc;
7.?>
PHP Constants
Only scalar data (boolean, integer, float and string) can
be contained in constants.
<?php
const MESSAGE="Hello const by Javapoint PHP";
echo MESSAGE;
?>
1.<?php
2. define("MSG", "JavaTpoint");
3. echo MSG, "</br>";
4. echo constant("MSG");
5. //both are similar
6.?>
Differences between constants
and variables
There is no need to write a dollar sign ($) before a
constant, where as in Variable one has to write a dollar
sign.
Constants cannot be defined by simple assignment, they
may only be defined using the define() function.
Constants may be defined and accessed anywhere
without regard to variable scoping rules.
Once the Constants have been set, may not be
redefined or undefined.
By default, constants are global.
Variables can be local, global, or static
Magic Constants
Magic constants are the predefined constants in PHP which get changed on
the basis of their use. They start with double underscore (__) and ends with
double underscore.
They are similar to other predefined constants but as they change their
values with the context, they are called magic constants.
Magic constants are case-insensitive.
1. __LINE__
2. __FILE__
3. __DIR__
4. __FUNCTION__
5. __CLASS__
6. __TRAIT__
7. __METHOD__
8. __NAMESPACE__
9. ClassName::class
PHP Arithmetic Operators
Operator Name Example Result
Remainder of $x divided
% Modulus $x % $y
by $y
x += y x=x+y Addition
x -= y x=x-y Subtraction
x *= y x=x*y Multiplication
x /= y x=x/y Division
PHP String Operators
Operato
Name Example Result
r
$txt1 = "Hello"
Now $txt2 contains
. Concatenation $txt2 = $txt1 . "
"Hello world!"
world!"
<?php
$per = 65
if ($per > 60) {
echo “Congrats,You are qualified!";
}
?>
The if...else Statement
- executes some code if a condition is true and another code
if the condition is false
<?php
$per = 65;
if ($per > 60)
{
echo “Congrats, You are qualified! ☺";
}
else
{
echo “Sorry, You are not qualified”
}
?>
The if...elseif....else Statement
- specifies a new condition to test, if the first
condition is false
<?php
$t = date("H");
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
<?php
$x = 6;
do {
echo "The number is: $x <br>";
$x++;
} while ($x<=5);
?>
What will be output of this program???
For Loops
The for loop is used when you know in
advance how many times the script should
run.
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
The example below displays the numbers from
0 to 10
PHP foreach Loop
The foreach loop is used to traverse the array elements. It
works only on array and object. It will issue an error if you
try to use it with the variables of different datatype.
The foreach loop works on elements basis rather than
index. It provides an easiest way to iterate the elements of
an array.
In foreach loop, we don't need to increment the value.
1. foreach ($array as $value) {
2. //code to be executed
3. }
or
1. foreach ($array as $key => $element) {
2. //code to be executed
3. }
PHP foreach Loop
<?php
$colors=array("red", "green", "blue", "yellow");
foreach ($colors as $value){
echo "$value <br>";
}
?>
For every loop iteration, the value of the
current array element is assigned to $value
and the array pointer is moved by one, until it
reaches the last array element.
<?php
$a = 42;
PHP
34
$b = 0;
if( $a && $b ){
echo "TEST1 : Both a and b are true<br/>";
}else{
echo "TEST1 : Either a or b is false<br/>";
}
if( $a and $b ){
echo "TEST2 : Both a and b are true<br/>";
}else{
echo "TEST2 : Either a or b is false<br/>";
}
if( $a || $b ){
echo "TEST3 : Either a or b is true<br/>";
}else{
echo "TEST3 : Both a and b are false<br/>";
}
if( $a or $b ){
echo "TEST4 : Either a or b is true<br/>";
}else{
echo "TEST4 : Both a and b are false<br/>";
PHP Arrays
$cars1 = "Volvo";
$cars2 = "BMW";
$cars3 = "Toyota";
However, what if you want to loop through the cars and
find a specific one? And what if you had not 3 cars, but 300?
The solution is to create an array!
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] .
".";
?>
O/P:
I like Volvo, BMW and Toyota.
PHP Array Types
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2]
. ".";
?>
O/P:
I like Volvo, BMW and Toyota.
Associative Arrays [key=>value]
We can associate name with each array elements in
PHP using => symbol.
will have their index as string so that you can
establish a strong association between key and
values.
To store the salaries of employees in an array, a
numerically indexed array would not be the best
choice. Instead, we could use the employees names
as the keys in our associative array, and the value
would be their respective salary.
<html>
<body>
<?php
/* First method to create associative array. */
$salaries = array("mohammad" => 2000, "qadir" => 1000, "zara"
=> 500);
echo "Salary of mohammad is ". $salaries['mohammad'] . "<br/>";
echo "Salary of qadir is ". $salaries['qadir']. "<br />";
echo "Salary of zara is ". $salaries['zara']. "<br />";
?>
</body></html>
Multi-dimensional Array
In multi-dimensional array, each element
in the main array can also be an array.
It allows you to store tabular data in an
array.
And each element in the sub-array can be
an array, and so on.
Values in the multi-dimensional array are
accessed using multiple index.
Multi-dimensional Array
$emp = array
(
array(1,"sonoo",400000),
array(2,"john",500000),
array(3,"rahul",300000)
);
<?php
$emp = array
(
array(1,"sonoo",400000),
array(2,"john",500000),
array(3,"rahul",300000)
);
<?php
$numbers = array(4, 6, 2, 22, 11);
rsort($numbers);
$arrlength = count($numbers);
<?php
$age= array("Ben"=>"37", "Peter"=>"35", "Joe"=>"43");
asort($age);
Key=Peter, Value=35
Key=Ben, Value=37
Key=Joe, Value=43
Sort Array (Ascending Order), According to Key - ksort()
<?php
$age
= array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
ksort($age);
<?php
$numbers = array(4, 6, 2, 22, 11);
$reversearr=array_reverse($numbers);
foreach( $reversearr as $s )
{
echo "$s<br />";
}
?>
array_search() function
PHP array_search() function searches the
specified value in an array. It returns key if
search is successful.
<?php
$numbers = array(4, 6, 2, 22, 11);
$key=array_search(22,$numbers);
echo “$key";
?>
array_intersect()
PHP array_intersect() function returns the intersection of two
array. In other words, it returns the matching elements of two
array.
1. <?php
2. $name1=array("sonoo","john","vivek","smith");
3. $name2=array("umesh","sonoo","kartik","smith");
4. $name3=array_intersect($name1,$name2);
5. foreach( $name3 as $n )
6. {
7. echo "$n<br />";
8. }
9. ?>
String
Singly quoted strings are treated almost literally, whereas doubly
quoted strings replace variables with their values as well as
specially interpreting certain character sequences.
<?php
$variable = “ABC";
$literally = 'My $variable will not print!\\n';
echo $literally;
echo "<br />";
<?php
function familyName($fname)
{echo "$fname <br>";}
familyName("Jadhav");
familyName(“Deshpande");
familyName(“Joshi");
familyName("Chandolikar");
familyName(“Godbole");
?>
PHP Function Arguments
<html>
<head>
<title>Writing PHP Function with Parameters</title>
</head>
<body>
<?php
function addFunction($num1, $num2)
{
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
?>
</body> Sum of the two numbers is :30
</html>
PHP Function Arguments:by value
<?php
function familyName($fname, $year) {
echo "$fname, Born in $year <br>";}
familyName("Kulkarni", "1975");
familyName(“Joshi", "1978");
familyName(“Jadhav", "1983");
?>
O/P:
Kulkarni, Born in 1975
Joshi, Born in 1978
Jadhav, Born in 1983
PHP Function Arguments: by reference
<?php
function addvalue($num)
{ $num += 5; echo "$num\n"; }
function addref(&$num)
{ $num += 6; echo "$num\n"; }
$orignum = 10;
addvalue( $orignum );
echo "Original Value is $orignum\n";
addref( $orignum );
echo "Original Value is $orignum\n";
15
Original Value is 10
?> 16
Original Value is 16
PHP Default Argument Value
<?php
function setHeight($minheight = 50) {
echo "The height is : $minheight <br>";
}
setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);?>
O/P:
The height is : 350
The height is : 50
The height is : 135
The height is : 80
Functions - Returning values
<?php
function sum($x, $y) {
$z = $x + $y;
return $z;}
$s=sum(5, 10);
echo "5 + 10 = $s <br>";
$s=sum(7, 13);
echo "7 + 13 = $s <br>";
$s=sum(2, 4); O/P:
5 + 10 = 15
echo "2 + 4 = $s <br>" ; 7 + 13 = 20
2+4=6
?>
Recursion
<?php
function factorial($n)
{
if ($n < 0)
return -1; /*Wrong value*/
if ($n == 0)
return 1; /*Terminating condition*/
return ($n * factorial ($n -1));
}
echo factorial(5);
?>
Dynamic Function Calls
It is possible to assign function names as
strings to variables and then treat these
variables exactly as the function name itself.
<?php
function sayHello() {
echo "Hello<br />"; }
$function_holder = "sayHello";
$function_holder();
?>
Outputting Data
In PHP there are two basic ways to get output: echo and
print Statements
Echo Print
1. Don’t return anything 1. Print has a return value ‘1’.
It can be used in expressions
2. Echo can take many 2. Print can take only one argument.
parameters.
marginally faster than print
Print :
<?php
Hello All to this class
$text="Hello All";
Hello Allto this class
print "$text to this class";
echo " " .$text. "to this class" ;
?>
include() And require()Functions
Those are useful functions to import files into a PHP
script.
These functions can be used to import external files into
a PHP script.
Example: Assume that on your Web site you have a
standard menu bar at the top of every page, and a
standard copyright notice in the bottom. Instead of
copying and pasting the header and footer code on each
individual page, PHP simply create separate files for the
header and footer, and import them at the top and
bottom of each script. This also makes a change to the
site design easier to implement: instead of manually
editing a gazillion files, you simply edit two, and the
changes are reflected across your entire site
instantaneously.
PHP Include Files
Code Reusability
Easy editable
You can include the content of a PHP file into
another PHP file before the server executes it.
Including files is very useful when you want to
include the same PHP text in multiple pages of a
website.
◦ The include() Function
◦ The require() Function
include 'filename‘; OR
<?php include("menu.html"); ?>
require 'filename'; OR
<?php require("menu.html"); ?>
Include Example-1
vars.php
<?php
$color = 'green’;
$fruit = 'apple';
?>
test.php
<?php
echo "A $color $fruit"; // A
include 'vars.php';
echo "A $color $fruit"; // A green apple
?>
Example: 1
Footer.php
<?php
echo "<p>Copyright © 1999-" . date("Y") . "
W3Schools.com</p>";
?>
To include the footer file in a page, use the include
statement:
<html>
<body>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
<p>Some more text.</p>
<?php include 'footer.php';?>Welcome to my home page!
Some text.
Some more text.
</body> Copyright © 1999-2017 W3Schools.com
</html>
Example: 2
Assume we have a standard menu file called "menu.php":
<?php
echo '<a href="/default.asp">Home</a> -
<a href="/html/default.asp">HTML Tutorial</a> -
<a href="/css/default.asp">CSS Tutorial</a> -
<a href="/js/default.asp">JavaScript Tutorial</a> -
<a href="default.asp">PHP Tutorial</a>';
?>
<html>
<body>
<div class="menu">
<?php include 'menu.php';?>
</div>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
<p>Some more text.</p>
</body>
</html>
Output of Example 2:
O/P: O/P:
Welcome to my home page! Welcome to my home page!
I have a .