php
php
Introduction to PHP
/*
This is a multiple lines comment block
that spans over more than
one line
*/
?>
Case Sensitivity
In PHP, all user-defined However; in PHP, all variables are
functions, classes, and case-sensitive.
keywords (e.g. if, else, while, <?php
echo, etc.) are NOT case- $color="red";
sensitive. echo "My car is " . $color . "<br>";
<?php echo "My pen is " , $COLOR;
ECHO "Hello World!<br>"; echo "My boat is " . $coLOR;
echo "Hello World!<br>"; ?>
EcHo "Hello World!<br>";
?> Output:
My car is red
Error : Undefined variable
Rules for PHP variables
A variable starts with the $ sign, followed by the name of the
variable.
A variable name must start with a letter or the underscore
character.
A variable name cannot start with a number.
A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ ).
Variable names are case sensitive ($y and $Y are two different
variables).
Note:When you assign a text value to a variable, put quotes
around the value. Eg:$color=“red”
PHP is a Loosely Typed Language
PHP has no command for declaring a variable.
A variable is created the moment you first assign a value to it:
<?php
$txt="Hello world!";
$x=5;
$y=10.5;
?>
In the example above, notice that we did not have to tell PHP which
data type the variable is.
PHP automatically converts the variable to the correct data type,
depending on its value.
In other languages such as C, C++, and Java, the programmer must
declare the name and type of the variable before using it.
Variables Scope
In PHP, variables can be declared anywhere in the script.
The scope of a variable is the part of the script where the
variable can be referenced/used.
PHP has three different variable scopes:
Local
global
static
<?php A variable declared outside a
$x=5; // global scope function has a GLOBAL SCOPE
and can only be accessed outside a
function myTest() { function.
$y=10; // local scope
echo "<p>Test variables inside the function:</p>";
echo "Variable x is: $x";
A variable declared within a
echo "<br>"; function has a LOCAL SCOPE
echo "Variable y is: $y"; and can only be accessed within
} that function.
myTest();
echo "<p>Test variables outside the function:</p>";
echo "Variable x is: $x";
echo "<br>";
echo "Variable y is: $y";
Output
Notice: Undefined variable: x in
\var\www\html\basics.php on line 28
Variable x is:
Variable y is: 10
Test variables outside the function:
Variable x is: 5
Notice: Undefined variable: y in
\var\www\html\basics.php on line 38
Variable y is:
The global Keyword
The global keyword is used to PHP also stores all global variables in
access a global variable from an array called $GLOBALS[index]. The
within a function. index holds the name of the variable.
<?php This array is also accessible from
within functions and can be used to
$x=5; update global variables directly.
$y=10;
<?php
function myTest() { $x=5;
global $x,$y; $y=10;
$y=$x+$y; function myTest() {
} $GLOBALS['y']=
$GLOBALS['x']+$GLOBALS['y'];
myTest(); }
echo $y; // outputs 15 myTest();
?> echo $y; // outputs 15
?>
The static Keyword
<?php Normally, when a function is
function myTest() { completed/executed, all of its
static $x=0; variables are deleted. However,
sometimes we want a local variable
echo $x;
NOT to be deleted. We need it for a
$x++; further job.
}
Then, each time the function is called,
myTest();
that variable will still have the
myTest(); information it contained from the last
myTest(); time the function was called.
Note: The variable is still local to the
?> function.
echo and print Statements
There are some differences between echo and print:
echo - can output one or more strings
print - can only output one string, and returns always 1
Tip: echo is marginally faster compared to print as echo does not return
any value.
echo and print is a language construct, and can be used with or without
parentheses: echo or echo() and print or print().
Example:
echo "This", " string", " was”. " made", " with multiple parameters.";
echo "Study PHP at $txt2";
print "Study PHP at $txt2";
Data types
String, Integer, Floating point numbers, Boolean, Array, Object, NULL.
Examples:
$x = "Hello world!";
$x = 'Hello world!';
$x = 5985; var_dump($x); int(5985)
$x = -345; // negative number
$x = 0x8C; // hexadecimal number
$x = 047; // octal number
$x = 10.365; $x = 2.4e3;
$x=true; $y=false; The PHP var_dump() function
$x=null; returns the data type and value of
variables.
Settype
In PHP, Variable type can be changed by Settype
Settype
Syntax:
settype(Variablename, “newDataType”);
E.g.
$pi = 3.14 //float
settype($pi,”string”); //now string – “3.14”
settype($pi,”integer”);// now integer - 3
Settype & Gettype
In PHP, Variable type and can know by Gettype.
Syntax:
gettype(Variablename);
E.g.
$pi = 3.14; //float
print gettype($pi);
Print “---$pi <br>”;
settype($pi,”string”);
print gettype($pi);
Print “---$pi <br>”;
settype($pi,”integer”);
print gettype($pi);
Print “---$pi <br>”;
Type Casting
To change type through casting you indicate the name of a data
type, in parentheses, in front of the variable you are copying.
Eg: $newvar=(integer) $originalvar
It creates a copy of the $originalvar variable, with a specific type
(int) and a new name $newvar.
The $originalvar variable will still be available, and will be its
original type;
$newvar is a completely new variable.
Casting a Variable
1: <html>
2: <head>
3: <title> Casting a variable</title>
4: </head>
5: <body>
6: <?php
7: $undecided = 3.14;
8: $holder = ( double ) $undecided;
9: print gettype( $holder ) ; // double
10: print " -- $holder<br>"; // 3.14
11: $holder = ( string ) $undecided;
12: print gettype( $holder ); // string
13: print " -- $holder<br>"; // 3.14
14: $holder = ( integer ) $undecided;
15: print gettype( $holder ); // integer
16: print " -- $holder<br>"; // 3
17: $holder = ( double ) $undecided;
18: print gettype( $holder ); // double
19: print " -- $holder<br>"; // 3.14
20: $holder = ( boolean ) $undecided;
21: print gettype( $holder ); // boolean
22: print " -- $holder<br>"; // 1
23: ?>
24: </body>
25: </html>
We never actually change the type of $undecided, which remains a
double throughout. Where we use the gettype() to determine the
type of $undecided.
Variable Variables
A variable variable creates a new variable and assigns the
current value of a variable as its name.
Example:
<?php
$a = 'hello';
$$a = 'world';
echo "$a $hello";
echo $hello;
?>
Constant
Constants are automatically global across the entire script.
The first parameter defines the name of the constant,
the second parameter defines the value of the constant,
and the optional third parameter specifies whether the constant name
should be case-insensitive. Default is false.
<?php
define("GREETING", "Welcome", true);
echo GREETING; // Welcome
echo "<br>";
echo greeting; //Welcome greeting is printed when sets false
?>
Operators
$txt1 = "Hello“ ;
$txt2 = $txt1 . " world!“; "Hello world!“ Concatenation
$txt1 = "Hello“;
$txt1 .= " world!“; "Hello world!“ Concatenation assignment
$x=100; $y="100";
($x == $y); // returns true because values are equal
($x === $y); // returns false because types are not equal
($x != $y); // returns false because values are equal // $x <>
$y
($x !== $y); // returns true because types are not equal
Defining Function
Syntax:
function functionName() {
code to be executed;
}
Example:
function familyName($fname, $year) {
echo "$fname Refsnes. Born in $year <br>";
}
familyName("Hege", "1975");
Default argument
function setHeight($minheight = 50) {
echo "The height is : $minheight <br>";
}
setHeight(350);
setHeight(); // will use the default value of 50
User Defined Functions
<?php
function calculateAmt($cost, $num)
{
return ($cost * $num);
}
$price=10;
$tot=5;
Echo “ Total Amount “, calculateAmt($price, $tot);
?>
Output:
Total Amount 50
User Defined Functions
Fn. Call by Ref.:
<?php
$cost = 20.99;
$tax = 0.0575;
function calculateCost(&$cost, $tax) Output:
{
// Modify the $cost variable (bfr fn call) Cost is 20.99
$cost = $cost + ($cost * $tax); Tax is 5.75
// Perform some random change to the (aft fn call) Cost is: 22.20
$tax variable.
$tax += 4;
}
Echo “(bfr fn call) Cost is $cost <br>”;
calculateCost($cost, $tax);
Echo "Tax is $tax*100 <br>";
Echo “(aft fn call) Cost is: $cost”;
?>
String Functions
Output:
Array
(
E.g: [0] => Hello
[1] => world.
[2] => It's
<?php
[3] => a
$str = "Hello world. It's a beautiful day.";
[4] => beautiful
print_r (explode(" ",$str));
[5] => day.
?>
)
String Functions
E.g: Output:
Hello World! Beautiful Day!
<?php
$arr = array('Hello','World!','Beautiful','Day!');
echo implode(" ",$arr);
?>
String Functions
E.g: Output:
<?php Length = 12
$a= “hello World!”;
echo “Length = “, strlen($a);
?>
String Functions
E.g: Output:
E.g: Output:
<?php
$a= “hello World!”; Upper of “hello World!” is HELLO
echo “Upper of \”$a\” is “, strtoupper($a); WORLD!
echo “Lower of \”$a\” is “, strtolower($a); Lower of “hello World!” is hello world
?>
String Functions
The strpos(string,exp) returns the numerical position of first appearance
of exp.
The strrpos(string,exp) returns the numerical position of last appearance
of exp.
strripos() - Finds the position of the last occurrence of a string inside another
string (case-insensitive)
E.g: Output:
<?php 2
$a= “hello World!”; 10
echo strpos($a,”l”),”<br>”;
echo strrpos($a,”l”);
?>
String Functions
E.g: Output:
<?php lo
$a= “hello World!”; ld!
echo substr($a,3,2); l
echo substr($a,-3); hello Wor
echo substr($a,-3,1);
echo substr($a,0,-3);
?>
String Functions
E.g: Output:
<?php 2
$a= “hello Worlod!”;
echo substr_count($a,”lo”);
?>
String Functions
E.g: Output:
<?php heaaorld!
$a= “hello World!”;
echo substr_replace($a,”aa”,2,5);
?>
String Functions
E.g: Output:
<?php Hello world!
$a= “hello world!”; Hello World!
echo ucfirst($a),”<br>”;
echo ucwords($a);
?>
String Functions
E.g: Output:
<?php 23
parse_str("id=23&name=Kai Jim"); Kai Jim
echo $id."<br />";
echo $name;
?>
String Functions
Output:
E.g:
Array
<?php (
$arr = array("blue","red","green","yellow"); [0] => blue
print_r(str_ireplace("RED","pink",$arr,$i)); [1] => pink
echo "Replacements: $i"; [2] => green
?> [3] => yellow
)
Replacements: 1
String Functions
E.g:
Output:
<?php .........Hello World
$str = "Hello World";
echo str_pad($str,20,".",STR_PAD_LEFT);
?>