0% found this document useful (0 votes)
58 views

PHP

PHP was invented by Rasmus Lerdorf in 1994. It is a scripting and interpreted language that is executed on the server-side. PHP files have a .php extension. PHP can generate dynamic page content, interact with databases, handle forms, send and receive cookies, and more. A PHP script typically contains HTML tags and some PHP code wrapped in <?php ?> tags. Common data types in PHP include integers, doubles, strings, arrays, and objects. PHP supports variables, operators, functions, and control structures to write scripts.

Uploaded by

Rishi Shah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views

PHP

PHP was invented by Rasmus Lerdorf in 1994. It is a scripting and interpreted language that is executed on the server-side. PHP files have a .php extension. PHP can generate dynamic page content, interact with databases, handle forms, send and receive cookies, and more. A PHP script typically contains HTML tags and some PHP code wrapped in <?php ?> tags. Common data types in PHP include integers, doubles, strings, arrays, and objects. PHP supports variables, operators, functions, and control structures to write scripts.

Uploaded by

Rishi Shah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 23

PHP

PHP
• PHP invented by Rasmus Lerdorf, 1994
• PHP Hypertext Pre-processor (earlier called, Personal Home Page)
• It is Scripting & interpreted Language
• Server side 
• Case sensitive ??
• PHP files have extension “.php”
• What can be done with PHP
– PHP can generate dynamic page content
– PHP can create, open, read, write, delete, and close files on the server
– PHP can collect form data
– PHP can send and receive cookies
– PHP can add, delete, modify data in your database
– PHP can be used to control user-access
– PHP can encrypt data
PHP Syntax
• A PHP script is executed on the server, and the plain HTML result is sent back to the browser.
• A PHP script starts with <?php and ends with ?>
<?php
// PHP code goes here
?>
• A PHP file normally contains HTML tags, and some PHP scripting code.
• echo is function to display output.
• Example:-
<!DOCTYPE html>
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
</html>
PHP Comments
• Single Line Comment
<?php
// This is a single-line comment

# This is also a single-line comment


?>
• Mutiple -line Comment
<?php
/*
This is a multiple-lines comment block
that spans over multiple
lines
*/
?>
PHP Reserved Words

and do function or virtual

break else global require xor

case elseif if return while

class extends include static var

continue false list switch

default for new this

foreach true
Data Types
• Scalar Data Types
– Boolean
– Integer
– Double
– String
• Compound Types
– Array
– Object
• Special Types
– Resource
– NULL
Output
echo
print ( )
printf( )

<?php
$str="RamRao";
$a=2014;
$b=18.765;

printf("Name is %10s year= %6d weight =


%5.2f", $str, $a, $b);
?>
Variables
• As PHP is dynamically typed, it has not type declaration

• The type of variable is decided by assigning value type

• An unassigned variable, sometimes called an unbound variable (NULL)

• NULL is prompted to zero in case of number, empty string in case of string.

• IsSet( ) can be used to determine whether currently variable have value or not, if not NULL value
returns true else false.

• What is error_reporting? What is its level? What value one should pass to it?
Data Types
• Integer
– Single Integer type, named integer
– Up to 32 bits

• Double
– Double literals can include decimal point, an exponent(E or e) or both
– There does not need to be any digit before or after decimal point, so both .45 and 45.
are legal literals
Data Types
• String
– Character in PHP are single byte
– There is no character type
– String literals are defined either with ‘ ’ or “ ”
– In string literals (single - quoted), escape sequences are not recognized and
embedded variables are not substituted (it is called interpolation)
– In string literals (double- quoted), escape sequences are recognized and embedded
variables are replaced by their current values.
– If a double quoted string literal includes a variable name and you do not want it
interpolated, precedes the variable name(before $) with backslash.
• Boolean Type:
– TRUE and FALSE are case insensitive
– If integer expression is used in Boolean, For 0 is false and otherwise true
– If string used in Boolean context, it evaluates to false if it is either empty or “0” .
Other’s are true . This implies that the string “0.0” evaluates to True.
– The only double value that is interpreted as False is exactly 0.0, A value can be very
close to zero, but because it is not exactly zero, it will evaluate to true.
Operators
• Arithmetic Operator (+,-,*,/,%,**, ++, --)
– If operands are integer, then result is integer (what about integer division??)
– If any operand is of type double, so result will be double
– If integer results overflows, will be promoted to double
– % works with integer ( If datatype is not integer, they are coerced to integer)
– Predefined Functions
• floor(double)
• ceil(double)
• round(double)
• srand(integer) – initializes a random number generator with the parameter
• rand(two numbers) – A pseudorandom number greater than the first number and smaller than
the second
• abs(number)
• min( one or more number)
• max( one or more number )
• String Operations:
– Concatenation is with period (.)
– If str is “Mugdha” then $str{3} is ??
– Many functions to operate string
• strlen( ), strcmp( ), trim( ), ltrim( ), strtolower( ), strtoupper( ), substr( ), strops( ),chop( )
Operators
• Assignment Operator and Combined(Compound) Assignment (=, += etc)
• Relational or Comparison Operators (> , <, >=, <=, !=, ==, === , !==,
<=> , < >)
– ===  Identical
– !==  Not Identical
– < = >  Spaceship
– < >  inequality
• Logical Operators (and, or, xor, !, && and ||)
• Bitwise Operator (&,|,^,~,<<,>>)
• Conditional Operator or Ternary Operator (? :)
• Conditional(assignment) Null coalescing (??)
– Example:-
• $x = expr1 ?? Expr2
• Returns the value of $x.
The value of $x is expr1 if expr1 exists, and is not NULL.
If expr1 does not exist, or is NULL, the value of $x is expr2.
Constants
• once defined cannot be changed or undefined.
• A constant is an identifier (name) for a simple value. 
• no $ sign before the constant name
• To Create constants define( ) is used.
• define(name, value, case-insensitive)
• Default case-insensitive is false.
• An Arrays as constant is also possible with define.
• Constants are globally accessible.

<?php
define("PI", 3.147); # case-sensetive constant.
echo PI;

define("GRVT", "9.81",true); # case-insensetive constant.


echo GRVT;
echo Grvt;
echo gettype(PI);
?>
Type Conversion
• Scalar Type Conversion
– Implicit conversion is called coercions
– Whenever string value appears in numeric expression, it will be converted to integer, if string
contains ‘E’ or ‘e’ , will be converted to double.; otherwise converted to integer. If a string does not
begins with sign or digit , conversion fails and zero is used. Non numeric character following
numbers in the string are ignored.
• Explicate conversion..,
– IF $sum is double, it will be converted to Integer as:
• (int)$sum
• intval($sum)
• settype($sum, “integer”)

• Similar to intval( ), PHP have doubleval( ) and strval( )

• Knowing Type of a Variable:


– gettype() – it takes variable name as parameter and returns a string as type of variable.
– Other ways are –
• is_int( ), is_integer( ), and is_long( )
• is_float( ) , is_double( ) and is_real( )
• is_bool( )
• is_String( ), is_object( ) and is_array( )
Decision and Control Statements
• Decision Making / Selection Statements
– If -else
– If - elseif
– switch-case
• Switch expression can be of any type int, double or string

• Iterative Statements
– For and For each
– While
– Do-while

• Jump Control Instructions


– Break
– Continue
Functions
General Form of a Function in PHP:
function functionName([parameters]) {
  …
}
Functions Names are not case-sensitive
<?php
function addNumbers(int $a, int $b) {
  return $a + $b;
}
echo addNumbers(5, "5 days");
// since strict is NOT enabled "5 days" is changed to int(5), and it will return 10
?>
<?php declare(strict_types=1); // strict requirement

function addNumbers(int $a, int $b) {


  return $a + $b;
}
echo addNumbers(5, "5 days");
// since strict is enabled and "5 days" is not an integer, an
error will be thrown
?>
Functions
• The default parameter passing mechanism is pass by value.
• Function names are not case sensitive.
• Function can return value.
• Pass by Reference
• It can be specified in two ways
• Adding & at the beginning of formal parameter
• Adding & to the actual parameter in function call.
• Scope of the variable:
• In function it is local.
• PHP, has a global declaration.
• It will be globally accessible using global.
• What is super global ??

• Default Argument??
• Can one Specify Argument Type ???
• Return Type declaration:-
function addNumbers(float $a, float $b) : float {
   return $a + $b;
}
Arrays
• PHP Array is Heterogeneous
• Each array element is combination of key and value
• Kays are non negative number and in ascending order
• The string keys in PHP are allowed
• PHP array can have some elements with integer keys and some with string keys
• Array Creation (Two ways, 1. Using Assignment and 2. Using Array Construct )
– Using Assignment Operator
• $list[0] = 17;
• $list[1] = 18;

• $arr[ ] = 13;
• $arr[ ] =14;
Arrays
• Array Creation (Two ways, 1. Using Assignment and 2. Using Array Construct )
– Using Assignment Operator
• Refer previous slide.
– Using Array Construct
• $arr = array ( ) # creates empty array
• $list = array(17,18,19,20)
– It is not a function, and numeric keys will be furnished by interpreter
• If you want different keys
• $list = array(1=>17,2=>18,3=>19,4=>20)
• The following statement creates an array that has the form of a hash:
• $arr = array(“Rohit”=>45, “Sachin”=>10, “Mahendra”=7, “Virendra”=309)
• PHP Array can be a mixture of number key and string keys.

• Que:-What is Associative Array in PHP???


Arrays
• Accessing Array Elements
– It is done using subscript operator
– Example
• $age[“Mary”]=29;
– Multiple elements of an array can be assigned to scalar variable in one statement, using
list construct.
– $trees = array(“oak”, “pine”, “binary”);
– list($hardwoord, $softwood, $data_structure) = $trees
– In above example, $hardwoord, $softwood, $data_structure are set to “oak”, “pine”,
“binary”, respectively.
• unset( )
Array Functions
– a whole array or array element can be deleted.
– $list = array (2,4,6,8);
– Unset($list[2])
– Now, list have 3-elements with keys 0,1, and 3.
<?php
$a =array(2,4,6,8);
unset($a[2]);
$e=0;
foreach ($a as $e){
echo $e." ";
}
?>
• array_keys( )
– Receives array name as parameter and returns an array of keys of given array.
– The returned array uses 0,1 and so forth as its keys
• array_values( )
– Does for values in arrays
• array_key_exists( )
– The existence of an specific key can be determined, returns Boolean value.
• array_key_exists( )
Array Functions
– The existence of an specific key can be determined, returns Boolean value.
<?php
$arr = array("Jan"=>31, "Feb"=>28 , "March"=>30);
if(array_key_exists("Feb",$arr)):
print($arr["Feb"]);
endif;
?>
• Note:- PHP does not interpolate array elements embedded in double quoted strings.
• is_array( )  Accept array as parameter and returns Boolean.
• sizeof( )  determines the number of elements in array, by accepting array name as
parameter.
• Arr_var=explode( delemeter, string_var)
• str_var=implode( delemeter, arr_var )
• array_push( ) – takes first parameter as array and there can be any number of additional
parameters.
• Array_pop( ) - takes single parameter as array name
• Home Work
– asort( )
– sort( )
– ksort( )
– rsort( ).arsort( ), and krsort( )

2 D Arrays
2D Array:- Car Name , Stock and Sold.

• $cars = array (
  array("Volvo",22,18),
  array("BMW",15,13),
  array("Saab",5,2),
  array("Land Rover",17,15)
);
• <?php
for ($row = 0; $row < 4; $row++) {
  echo "<p><b>Row number $row</b></p>";
  echo "<ul>";
  for ($col = 0; $col < 3; $col++) {
    echo "<li>".$cars[$row][$col]."</li>";
 }
  echo "</ul>";
}
?>
• Ref:- https://www.w3schools.com/php/php_arrays_multidimensional.asp

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy