SlideShare a Scribd company logo
Module 1:
Introduction to web techniques-
PHP Basics
By
Mr. Deepak V Ulape (Asst. Professor)
College of Management,
MIT ADT University, Loni Kalbhor, Pune
What is PHP?
• PHP is an acronym for "PHP: Hypertext Preprocessor"
• PHP is a widely-used, open source scripting language
• PHP scripts are executed on the server
• PHP is free to download and use
PHP files can contain text, HTML, CSS, JavaScript, and PHP
code
PHP code is executed on the server, and the result is returned
to the browser as plain HTML
PHP files have extension ".php"
What is a PHP File?
Features of 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
Why PHP?
• PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
• PHP is compatible with almost all servers used today (Apache, IIS, etc.)
• PHP supports a wide range of databases
• PHP is free. Download it from the official PHP resource: www.php.net
• PHP is easy to learn and runs efficiently on the server side
A PHP script is executed on the server, and the plain HTML result is sent back to
the browser.
Basic PHP Syntax
A PHP script can be placed anywhere in the document.
A PHP script starts with <?php and ends with ?>:
<?php // PHP code goes here ?>
The default file extension for PHP files is ".php".
A PHP file normally contains HTML tags, and some PHP scripting code.
Example
A simple .php file with both HTML code and PHP code:
<!DOCTYPE html>
<html>
<body> <h1>My first PHP page</h1>
<?php echo "Hello World!"; ?>
</body>
</html>
Lexical structure of PHP
1. Tokens
Tokens are the smallest elements in the PHP language. They include:
•Identifiers: Names for variables, functions, classes, etc. They start with a letter or
underscore and can contain letters, numbers, and underscores.
•Example: $myVariable
•Keywords: Reserved words with special meaning (e.g., if, else, for, function, class).
•Operators: Symbols that represent operations (e.g., +, -, *, /, =).
•Literals: Fixed values such as strings, numbers, and booleans.
•Example: 'Hello, World!', 42, true
•Delimiters: Special characters that separate different elements in the code.
2. Whitespace and Comments
Whitespace (spaces, tabs, newlines) is generally ignored but can improve readability.
Comments are used to annotate code and are ignored during execution.
•Single-line comments:
•// This is a comment
•# This is also a comment
•Multi-line comments:
•/* This is a multi-line comment */
3. Strings
Strings can be defined using single quotes (') or double quotes ("). Double-quoted strings
support variable interpolation and escape sequences.
4. Variables
Variables in PHP start with the dollar sign ($), followed by the variable name.
5. Operators
PHP supports a variety of operators:
•Arithmetic: +, -, *, /, %
•Comparison: ==, ===, !=, !==, <, >
•Logical: &&, ||, !
6. Control Structures
PHP has various control structures for flow control:
•Conditional Statements: if, else, switch
•Loops: for, while, foreach
7. Functions and Classes
Functions are defined using the function keyword. Classes use the class keyword and
support inheritance and encapsulation.
8. Namespaces
Namespaces allow for better organization of code and to avoid name collisions.
PHP Arrays :
• Arrays in PHP are a type of data structure that allows us to
store multiple elements of similar or different data types
under a single variable thereby saving us the effort of
creating a different variable for every data.
• Types of Array in PHP
• Indexed or Numeric Arrays
• Associative Arrays
• Multidimensional Arrays
Types of Array in PHP
• Indexed or Numeric Arrays: An array with a numeric index
where values are stored linearly.
• Associative Arrays: An array with a string index where
instead of linear storage, each value can be assigned a
specific key.
• Multidimensional Arrays: An array that contains a single or
multiple arrays within it and can be accessed via multiple
indices.
• Indexed or Numeric Arrays
• These type of arrays can be used to store any type of
element, but an index is always a number. By default, the
index starts at zero. These arrays can be created in two
different ways.
<?php
// One way to create an indexed array
$name_one = array("Zack", "Anthony",
"Ram", "Salim", "Raghav");
// Accessing the elements directly
echo "Accessing the 1st array elements
directly:n";
echo $name_one[2], "n";
echo $name_one[0], "n";
echo $name_one[4], "n";
// Second way to create an indexed array
$name_two[0] = "ZACK";
$name_two[1] = "ANTHONY";
$name_two[2] = "RAM";
$name_two[3] = "SALIM";
$name_two[4] = "RAGHAV";
// Accessing the elements directly
echo "Accessing the 2nd array elements
directly:n";
echo $name_two[2], "n";
echo $name_two[0], "n";
echo $name_two[4], "n";
?>
<?php
// Creating an indexed array
$name_one = array("Zack", "Anthony", "Ram", "Salim", "Raghav");
// One way of Looping through an array using foreach
echo "Looping using foreach: n";
foreach ($name_one as $val){
echo $val. "n";
}
// count() function is used to count
// the number of elements in an array
$round = count($name_one);
echo "nThe number of elements are $round n";
// Another way to loop through the array using for
echo "Looping using for: n";
for($n = 0; $n < $round; $n++){
echo $name_one[$n], "n";
}
?>
Ex: traverse an indexed array using loops in PHP.
Associative Arrays
• These types of arrays are similar to the indexed arrays but
instead of linear storage, every value can be assigned with a
user-defined key of string type.
<?php
// One way to create an associative array
$name_one = array("Zack"=>"Zara", "Anthony"=>"Any", "Ram"=>"Rani",
"Salim"=>"Sara",
"Raghav"=>"Ravina");
// Second way to create an associative array
$name_two["zack"] = "zara";
$name_two["anthony"] = "any";
$name_two["ram"] = "rani";
$name_two["salim"] = "sara";
$name_two["raghav"] = "ravina";
// Accessing the elements directly
echo "Accessing the elements directly:n";
echo $name_two["zack"], "n";
echo $name_two["salim"], "n";
echo $name_two["anthony"], "n";
echo $name_one["Ram"], "n";
echo $name_one["Raghav"], "n";
?>
Examples of Associative Arrays
Multidimensional Arrays
• Multi-dimensional arrays are such arrays that store another
array at each index instead of a single element. In other
words, we can define multi-dimensional arrays as an array
of arrays. As the name suggests, every element in this array
can be an array and they can also hold other sub-arrays
within. Arrays or sub-arrays in multidimensional arrays can
be accessed using multiple dimensions.
<?php
// Defining a multidimensional array
$favorites = array(
array(
"name" => "Dave Punk",
"mob" => "5689741523",
"email" => "davepunk@gmail.com",
), array(
"name" => "Monty Smith",
"mob" => "2584369721",
"email" => "montysmith@gmail.com",
), array(
"name" => "John Flinch",
"mob" => "9875147536",
"email" => "johnflinch@gmail.com",
) );
// Accessing elements
echo "Dave Punk email-id is: " . $favorites[0]["email"], "n";
echo "John Flinch mobile number is: " . $favorites[2]["mob"]; ?>
Functions:
• A function is a block of code written in a program to perform some
specific task.
• PHP provides us with two major types of functions:
• Built-in functions : PHP provides us with huge collection of built-in
library functions. These functions are already coded and stored in
form of functions. To use those we just need to call them as per our
requirement like, var_dump, fopen(), print_r(), gettype() and so on.
• User Defined Functions : Apart from the built-in functions, PHP
allows us to create our own customised functions called the user-
defined functions.
Using this we can create our own packages of code and use it
wherever necessary by simply calling it.
Creating a Function:
1.Any name ending with an open and closed parenthesis is a
function.
2.A function name always begins with the keyword function.
3.To call a function we just need to write its name followed by
the parenthesis
4.A function name cannot start with a number. It can start
with an alphabet or underscore.
5.A function name is not case-sensitive.
Syntax:
function function_name(){
executable code;
}
Example:
<?php
function funcGeek()
{
echo "This is Geeks for Geeks";
}
// Calling the function
funcGeek();
?>
Function Parameters or Arguments :
The information or variable, within the function’s parenthesis,
are called parameters. These are used to hold the values
executable during runtime. A user is free to take in as many
parameters as he wants, separated with a comma(,) operator.
These parameters are used to accept inputs during runtime.
While passing the values like during a function call, they are
called arguments. An argument is a value passed to a
function and a parameter is used to hold those arguments. In
common term, both parameter and argument mean the
same. We need to keep in mind that for every parameter, we
need to pass its corresponding argument.
Syntax:
function function_name($first_parameter, $second_parameter) {
executable code;
}
Example:
<?php
// function along with three parameters
function proGeek($num1, $num2, $num3)
{
$product = $num1 * $num2 * $num3;
echo "The product is $product";
}
// Calling the function
// Passing three arguments
proGeek(2, 3, 5);
?>
Setting Default Values for Function parameter
PHP allows us to set default argument values for function parameters. If we do not pass any
argument for a parameter with default value then PHP will use the default set value for this
parameter in the function call.
Example:
<?php
// function with default parameter
function defGeek($str, $num=12)
{
echo "$str is $num years old n";
}
// Calling the function
defGeek("Ram", 15);
// In this call, the default value 12
// will be considered
defGeek("Adam");
?>
Returning Values from Functions
• 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 along with three parameters
function proGeek($num1, $num2, $num3)
{
$product = $num1 * $num2 * $num3;
return $product; //returning the product
}
// storing the returned value
$retValue = proGeek(2, 3, 5);
echo "The product is $retValue";
?>
Parameter passing to Functions
• PHP allows us two ways in which an argument can be passed into
a function:
• Pass by Value: On passing arguments using pass by value, the
value of the argument gets changed within a function, but the
original value outside the function remains unchanged. That
means a duplicate of the original value is passed as an argument.
• Pass by Reference: On passing arguments as pass by reference,
the original value is passed. Therefore, the original value gets
altered. In pass by reference we actually pass the address of the
value, where it is stored using ampersand sign(&).
<?php
// pass by value
function valGeek($num) {
$num += 2;
return $num;
}
// pass by reference
function refGeek(&$num) {
$num += 10;
return $num;
}
$n = 10;
valGeek($n);
echo "The original value is still $n n";
refGeek($n);
echo "The original value changes to $n";
?>
Output:
The original value is still 10
The original value changes to 20
• Variable Functions
• A variable function allows you to call a function dynamically by using a
variable that contains the function name.
• Example of Variable Functions
<?php
function sayHello($name) {
return "Hello, " . $name;
}
$functionName = 'sayHello';
echo $functionName('Alice'); // Outputs: Hello, Alice
?>
In this example, the function sayHello is called using a variable $functionName that holds
its name.
Anonymous Functions (Closures)
• Anonymous functions, or closures, are functions that have no name and can be used as values.
They are often used for callback functions or for creating simple functions on the fly.
• Example of Anonymous Functions
<?php
// Defining an anonymous function
$square = function($n) {
return $n * $n;
};
echo $square(4); // Outputs: 16
// Using an anonymous function as a callback
$numbers = [1, 2, 3, 4, 5];
$squaredNumbers = array_map(function($n) {
return $n * $n;
},
print_r($squaredNumbers); // Outputs: Array ( [0] => 1 [1] => 4 [2] => 9 [3] => 16 [4] => 25 )
?>
Anonymous functions
Anonymous functions, also known as closures, allow the creation of functions
which have no specified name. They are most useful as the value of callback
parameters, but they have many other uses.
Anonymous functions are implemented using the Closure class.
Example:
<?php
$greet = function($name)
{
printf("Hello %srn", $name);
};
$greet('World');
$greet('PHP');
?>
Exmple #2 Anonymous function variable assignment example
1. echo
•Description: Outputs one or more strings. It is not a function, but a language construct, so
it can be used without parentheses.
•Usage: Fastest way to output data.
php
<?php echo "Hello, World!"; echo " This is PHP."; // Multiple strings can be concatenated ?>
2. print
•Description: Similar to echo, but it behaves like a function and returns 1, so it can be used in
expressions.
•Usage: Slightly slower than echo, but can be used in more contexts.
php
<?php print "Hello, World!"; print(" This is PHP."); ?>
Printing functions
3. print_r
•Useful for printing arrays and objects in a human-readable format.
$array = ["apple", "banana", "cherry"];
print_r($array);
4. var_dump
•Displays structured information (type and value) about variables, including
arrays and objects.
$variable = "Hello, World!";
var_dump($variable);
$array = ["name" => "Alice", "age" => 30];
var_dump($array);
5. printf
•Formats a string according to specified format codes.
Similar to C's printf.
$name = "Alice"; $age = 30; printf("%s is %d years old.", $name, $age);
Php Strings
A string is a sequence of characters
They are sequences of characters, like "PHP supports string operations".
NOTE − Built-in string functions is given in function reference PHP String Functions
Following are valid examples of string
$string_1 = "This is a string in double quotes";
$string_2 = ‘This is a somewhat longer, singly quoted string’;
$string_39 = "This string has thirty-nine characters";
$string_0 = “ "; // a string with zero characters
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 = "name";
$literally = 'My $variable will not print!n';
print($literally);
print "<br />";
$literally = "My $variable will print!n";
print($literally);
?>
• My $variable will not print!n
• My name will print!n
String Concatenation Operator
• To concatenate two string variables together, use the dot (.) operator
<?php
$string1="Hello Students";
$string2="1234";
echo $string1 . " " . $string2;
?>
Output:
Hello Students 1234
• If we look at the code above you see that we used the concatenation operator
two times. This is because we had to insert a third string.
• Between the two string variables we added a string with a single character, an
empty space, to separate the two variables.
Types of strings
• A string literal can be specified in four different ways:
• single quoted
• double quoted
• heredoc syntax
• nowdoc syntax
Single quoted
• The simplest way to specify a string is to enclose it in single quotes (the
character ').
• To specify a literal single quote, escape it with a backslash (). To specify
a literal backslash, double it (). All other instances of backslash will be
treated as a literal backslash: this means that the other escape
sequences you might be used to, such as r or n, will be output literally
as specified rather than having any special meaning.
• Note: Unlike the double-quoted and heredoc syntaxes, variables and
escape sequences for special characters will not be expanded when
they occur in single quoted strings.
<?php
echo 'this is a simple string';
echo 'You can also have embedded newlines in
strings this way as it is
okay to do';
// Outputs: Arnold once said: "I'll be back"
echo 'Arnold once said: "I'll be back"';
// Outputs: You deleted C:*.*?
echo 'You deleted C:*.*?';
// Outputs: You deleted C:*.*?
echo 'You deleted C:*.*?';
// Outputs: This will not expand: n a newline
echo 'This will not expand: n a newline';
// Outputs: Variables do not $expand $either
echo 'Variables do not $expand $either';
?>
Double quoted
• Strings that are delimited by double quotes (as in "this") are preprocessed in both the following
two ways by PHP −
• Certain character sequences beginning with backslash () are replaced with special characters
• Variable names (starting with $) are replaced with string representations of their values.
• The escape-sequence replacements are −
• n is replaced by the newline character
• r is replaced by the carriage-return character
• t is replaced by the tab character
• $ is replaced by the dollar sign itself ($)
• " is replaced by a single double-quote (")
•  is replaced by a single backslash ()
Heredoc
• A third way to delimit strings is the heredoc syntax: <<<. After this
operator, an identifier is provided, then a newline. The string itself follows,
and then the same identifier again to close the quotation.
• The closing identifier must begin in the first column of the line. Also, the
identifier must follow the same naming rules as any other label in PHP: it
must contain only alphanumeric characters and underscores, and must
start with a non-digit character or underscore.
• PHP heredoc strings behave like double-quoted strings, without
the double-quotes. It means that they don’t need to escape
quotes and expand variables.
• When you place variables in a double-quoted string, PHP will expand the
variable names. If a string contains the double quotes (“), you need to
escape them using the backslash character(). For example:
• First, start with the <<< operator, an identifier, and a new line:
• <<<IDENTIFIER
• Second, specify the string, which can span multiple lines and includes single quotes (‘) or double quotes
(“).
• Third, close the string with the same identifier.
• The identifier must contain only alphanumeric characters and underscores and start with an underscore
or a non-digit character.
• The closing identifier must follow these rules:
• Begins at the first column of the line
• Contains no other characters except a semicolon (;).
• The character before and after the closing identifier must be a newline character defined by the local
operating system.
<?php $he = 'Bob’;
$she = 'Alice’;
$text = "$he said, "PHP is awesome".
"Of course."
$she agreed."; echo $text;
Output:
Bob said, "PHP is
awesome".
"Of course." Alice agreed.
Nowdocs
• Nowdocs are to single-quoted strings what heredocs are to double-
quoted strings. A nowdoc is specified similarly to a heredoc, but no
parsing is done inside a nowdoc. The construct is ideal for embedding
PHP code or other large blocks of text without the need for escaping. It
shares some features in common with the SGML <![CDATA[ ]]>
construct, in that it declares a block of text which is not for parsing.
• A nowdoc is identified with the same <<< sequence used for heredocs,
but the identifier which follows is enclosed in single quotes, e.g.
<<<'EOT'. All the rules for heredoc identifiers also apply to nowdoc
identifiers, especially those regarding the appearance of the closing
identifier.
<?php
class foo
{
public $foo;
public $bar;
function __construct()
{
$this->foo = 'Foo';
$this->bar = array('Bar1', 'Bar2',
'Bar3');
}
}
$foo = new foo();
$name = 'MyName';
echo <<<'EOT'
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should not print a capital 'A': x41
EOT;
?>
The above example will output:
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should not print a capital 'A': x41
String Manipulation Functions:
• String manipulation and searching are fundamental tasks in PHP
•Concatenation
•Use the . operator to concatenate strings.
$string1 = "Hello"; $string2 = "World"; $result = $string1 . " " .
$string2; // "Hello World"
•String Length
•Use strlen() to get the length of a string.
$length = strlen($result); // 11
•Substring
•Use substr() to get a portion of a string.
$sub = substr($result, 0, 5); // "Hello"
•String Replacement
•Use str_replace() to replace occurrences of a substring.
$newString = str_replace("World", "PHP", $result); // "Hello PHP“
Changing Case
Use strtoupper() and strtolower() for changing case.
$upper = strtoupper($result); // "HELLO WORLD“
$lower = strtolower($result); // "hello world"
•Trimming Whitespace
•Use trim() to remove whitespace from the beginning and end of a string.
$trimmed = trim(" Hello World "); // "Hello World"
•String Splitting
•Use explode() to split a string into an array.
$array = explode(" ", $result); // ["Hello", "World"]
•Joining Strings
•Use implode() to join an array into a string.
php
$joined = implode(", ", $array); // "Hello, World"
String Searching Functions
1.Finding Substring Position
•Use strpos() to find the position of a substring.
$position = strpos($result, "World"); // 6
2.Finding the Last Occurrence
•Use strrpos() to find the last position of a substring.
$lastPosition = strrpos($result, "o"); // 7
3.Substring Search (Case Insensitive)
•Use stripos() for a case-insensitive search.
php
$caseInsensitivePosition = stripos($result, "world"); // 6
•Checking for Substring
•Use str_contains() to check if a string contains a substring (PHP 8.0+).
$contains = str_contains($result, "Hello"); // true
•Regular Expression Search
•Use preg_match() for pattern matching.
if (preg_match("/Hello/", $result)) { echo "Found 'Hello'!"; }
<?php
$text = " Welcome to PHP string manipulation! ";
// Trim the text
$trimmedText = trim($text);
// Replace a word
$replacedText = str_replace("PHP", "Python", $trimmedText);
// Find position of 'to'
$position = strpos($replacedText, "to");
// Change case
$upperText = strtoupper($replacedText);
// Output results
echo "Original: $textn";
echo "Trimmed: $trimmedTextn";
echo "Replaced: $replacedTextn";
echo "Position of 'to': $positionn";
echo "Uppercase: $upperTextn";
?>
String comparison
• the string comparison using the equal (==) operator & strcmp()
Function in PHP, along with understanding their implementation
through the example.
• PHP == Operator: The comparison operator called Equal Operator
is the double equal sign “==”. This operator accepts two inputs to
compare and returns a true value if both of the values are the
same (It compares the only value of the variable, not data types)
and returns a false value if both of the values are not the same.
• This should always be kept in mind that the present equality
operator == is different from the assignment operator =. The
assignment operator assigns the variable on the left to have a new
value as the variable on right, while the equal operator == tests for
equality and returns true or false as per the comparison results.
<?php
// Declaration of strings
$name1 = "Geeks";
$name2 = "Geeks";
// Use == operator
if ($name1 == $name2) {
echo 'Both strings are equal';
}
else {
echo 'Both strings are not equal';
}
?>
Output:
Both the strings are equal
PHP strcmp() Function:
• PHP strcmp() Function: The strcmp() is an inbuilt function
in PHP that is used to compare two strings. This function is
case-sensitive which points that capital and small cases will
be treated differently, during comparison. This function
compares two strings and tells whether the first string is
greater or smaller or equals the second string. This function
is binary-safe string comparison.
Syntax:
strcmp( $string1, $string2 )
Parameters: This function accepts two parameters as mentioned above and described
below:
•$string1: This parameter refers to the first string to be used in the comparison. It is a
mandatory parameter.
•$string2: This parameter refers to the second string to be used in the comparison. It is
a mandatory parameter.
Return Values: The function returns a random integer value depending on the
condition of the match, which is given by:
•Returns 0 if the strings are equal.
•Returns a negative value (< 0), if $string2 is greater than $string1.
•Returns a positive value (> 0) if $string1 is greater than $string2.
<?php
// Declaration of strings
$name1 = "Geeks";
$name2 = "geeks";
// Use strcmp() function
if (strcmp($name1, $name2) !== 0) {
echo 'Both strings are not equal';
}
else {
echo 'Both strings are equal';
}
?>
Output:
Both strings are not equal
Ad

More Related Content

Similar to Introduction to PHP_ Lexical structure_Array_Function_String (20)

Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Muhamad Al Imran
 
Php i basic chapter 3
Php i basic chapter 3Php i basic chapter 3
Php i basic chapter 3
Muhamad Al Imran
 
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Muhamad Al Imran
 
PHP-03-Functions.ppt
PHP-03-Functions.pptPHP-03-Functions.ppt
PHP-03-Functions.ppt
Jamers2
 
PHP-03-Functions.ppt
PHP-03-Functions.pptPHP-03-Functions.ppt
PHP-03-Functions.ppt
ShishirKantSingh1
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
Taha Malampatti
 
05php
05php05php
05php
sahilshamrma08
 
PHP Lec 2.pdfsssssssssssssssssssssssssss
PHP Lec 2.pdfsssssssssssssssssssssssssssPHP Lec 2.pdfsssssssssssssssssssssssssss
PHP Lec 2.pdfsssssssssssssssssssssssssss
ksjawyyy
 
object oriented programming in PHP & Functions
object oriented programming in PHP & Functionsobject oriented programming in PHP & Functions
object oriented programming in PHP & Functions
BackiyalakshmiVenkat
 
Php Unit 1
Php Unit 1Php Unit 1
Php Unit 1
team11vgnt
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
KIRAN KUMAR SILIVERI
 
05php
05php05php
05php
anshkhurana01
 
MIND sweeping introduction to PHP
MIND sweeping introduction to PHPMIND sweeping introduction to PHP
MIND sweeping introduction to PHP
BUDNET
 
PHP from soup to nuts Course Deck
PHP from soup to nuts Course DeckPHP from soup to nuts Course Deck
PHP from soup to nuts Course Deck
rICh morrow
 
Introduction To Php For Wit2009
Introduction To Php For Wit2009Introduction To Php For Wit2009
Introduction To Php For Wit2009
cwarren
 
Training on php by cyber security infotech (csi)
Training on  php by cyber security infotech (csi)Training on  php by cyber security infotech (csi)
Training on php by cyber security infotech (csi)
Cyber Security Infotech Pvt. Ltd.
 
phptutorial
phptutorialphptutorial
phptutorial
tutorialsruby
 
phptutorial
phptutorialphptutorial
phptutorial
tutorialsruby
 
PHP Basics Ebook
PHP Basics EbookPHP Basics Ebook
PHP Basics Ebook
Swanand Pol
 
rtwerewr
rtwerewrrtwerewr
rtwerewr
esolinhighered
 
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Muhamad Al Imran
 
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Muhamad Al Imran
 
PHP-03-Functions.ppt
PHP-03-Functions.pptPHP-03-Functions.ppt
PHP-03-Functions.ppt
Jamers2
 
PHP Lec 2.pdfsssssssssssssssssssssssssss
PHP Lec 2.pdfsssssssssssssssssssssssssssPHP Lec 2.pdfsssssssssssssssssssssssssss
PHP Lec 2.pdfsssssssssssssssssssssssssss
ksjawyyy
 
object oriented programming in PHP & Functions
object oriented programming in PHP & Functionsobject oriented programming in PHP & Functions
object oriented programming in PHP & Functions
BackiyalakshmiVenkat
 
MIND sweeping introduction to PHP
MIND sweeping introduction to PHPMIND sweeping introduction to PHP
MIND sweeping introduction to PHP
BUDNET
 
PHP from soup to nuts Course Deck
PHP from soup to nuts Course DeckPHP from soup to nuts Course Deck
PHP from soup to nuts Course Deck
rICh morrow
 
Introduction To Php For Wit2009
Introduction To Php For Wit2009Introduction To Php For Wit2009
Introduction To Php For Wit2009
cwarren
 
PHP Basics Ebook
PHP Basics EbookPHP Basics Ebook
PHP Basics Ebook
Swanand Pol
 

Recently uploaded (20)

How to Troubleshoot 9 Types of OutOfMemoryError
How to Troubleshoot 9 Types of OutOfMemoryErrorHow to Troubleshoot 9 Types of OutOfMemoryError
How to Troubleshoot 9 Types of OutOfMemoryError
Tier1 app
 
Autodesk Inventor Crack (2025) Latest
Autodesk Inventor    Crack (2025) LatestAutodesk Inventor    Crack (2025) Latest
Autodesk Inventor Crack (2025) Latest
Google
 
Best HR and Payroll Software in Bangladesh - accordHRM
Best HR and Payroll Software in Bangladesh - accordHRMBest HR and Payroll Software in Bangladesh - accordHRM
Best HR and Payroll Software in Bangladesh - accordHRM
accordHRM
 
Robotic Process Automation (RPA) Software Development Services.pptx
Robotic Process Automation (RPA) Software Development Services.pptxRobotic Process Automation (RPA) Software Development Services.pptx
Robotic Process Automation (RPA) Software Development Services.pptx
julia smits
 
AEM User Group DACH - 2025 Inaugural Meeting
AEM User Group DACH - 2025 Inaugural MeetingAEM User Group DACH - 2025 Inaugural Meeting
AEM User Group DACH - 2025 Inaugural Meeting
jennaf3
 
Solar-wind hybrid engery a system sustainable power
Solar-wind  hybrid engery a system sustainable powerSolar-wind  hybrid engery a system sustainable power
Solar-wind hybrid engery a system sustainable power
bhoomigowda12345
 
Sequence Diagrams With Pictures (1).pptx
Sequence Diagrams With Pictures (1).pptxSequence Diagrams With Pictures (1).pptx
Sequence Diagrams With Pictures (1).pptx
aashrithakondapalli8
 
The-Future-is-Hybrid-Exploring-Azure’s-Role-in-Multi-Cloud-Strategies.pptx
The-Future-is-Hybrid-Exploring-Azure’s-Role-in-Multi-Cloud-Strategies.pptxThe-Future-is-Hybrid-Exploring-Azure’s-Role-in-Multi-Cloud-Strategies.pptx
The-Future-is-Hybrid-Exploring-Azure’s-Role-in-Multi-Cloud-Strategies.pptx
james brownuae
 
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
OnePlan Solutions
 
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World ExamplesMastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
jamescantor38
 
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Eric D. Schabell
 
Buy vs. Build: Unlocking the right path for your training tech
Buy vs. Build: Unlocking the right path for your training techBuy vs. Build: Unlocking the right path for your training tech
Buy vs. Build: Unlocking the right path for your training tech
Rustici Software
 
Digital Twins Software Service in Belfast
Digital Twins Software Service in BelfastDigital Twins Software Service in Belfast
Digital Twins Software Service in Belfast
julia smits
 
Adobe InDesign Crack FREE Download 2025 link
Adobe InDesign Crack FREE Download 2025 linkAdobe InDesign Crack FREE Download 2025 link
Adobe InDesign Crack FREE Download 2025 link
mahmadzubair09
 
Download MathType Crack Version 2025???
Download MathType Crack  Version 2025???Download MathType Crack  Version 2025???
Download MathType Crack Version 2025???
Google
 
Memory Management and Leaks in Postgres from pgext.day 2025
Memory Management and Leaks in Postgres from pgext.day 2025Memory Management and Leaks in Postgres from pgext.day 2025
Memory Management and Leaks in Postgres from pgext.day 2025
Phil Eaton
 
Medical Device Cybersecurity Threat & Risk Scoring
Medical Device Cybersecurity Threat & Risk ScoringMedical Device Cybersecurity Threat & Risk Scoring
Medical Device Cybersecurity Threat & Risk Scoring
ICS
 
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdfTop Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
evrigsolution
 
Troubleshooting JVM Outages – 3 Fortune 500 case studies
Troubleshooting JVM Outages – 3 Fortune 500 case studiesTroubleshooting JVM Outages – 3 Fortune 500 case studies
Troubleshooting JVM Outages – 3 Fortune 500 case studies
Tier1 app
 
How to avoid IT Asset Management mistakes during implementation_PDF.pdf
How to avoid IT Asset Management mistakes during implementation_PDF.pdfHow to avoid IT Asset Management mistakes during implementation_PDF.pdf
How to avoid IT Asset Management mistakes during implementation_PDF.pdf
victordsane
 
How to Troubleshoot 9 Types of OutOfMemoryError
How to Troubleshoot 9 Types of OutOfMemoryErrorHow to Troubleshoot 9 Types of OutOfMemoryError
How to Troubleshoot 9 Types of OutOfMemoryError
Tier1 app
 
Autodesk Inventor Crack (2025) Latest
Autodesk Inventor    Crack (2025) LatestAutodesk Inventor    Crack (2025) Latest
Autodesk Inventor Crack (2025) Latest
Google
 
Best HR and Payroll Software in Bangladesh - accordHRM
Best HR and Payroll Software in Bangladesh - accordHRMBest HR and Payroll Software in Bangladesh - accordHRM
Best HR and Payroll Software in Bangladesh - accordHRM
accordHRM
 
Robotic Process Automation (RPA) Software Development Services.pptx
Robotic Process Automation (RPA) Software Development Services.pptxRobotic Process Automation (RPA) Software Development Services.pptx
Robotic Process Automation (RPA) Software Development Services.pptx
julia smits
 
AEM User Group DACH - 2025 Inaugural Meeting
AEM User Group DACH - 2025 Inaugural MeetingAEM User Group DACH - 2025 Inaugural Meeting
AEM User Group DACH - 2025 Inaugural Meeting
jennaf3
 
Solar-wind hybrid engery a system sustainable power
Solar-wind  hybrid engery a system sustainable powerSolar-wind  hybrid engery a system sustainable power
Solar-wind hybrid engery a system sustainable power
bhoomigowda12345
 
Sequence Diagrams With Pictures (1).pptx
Sequence Diagrams With Pictures (1).pptxSequence Diagrams With Pictures (1).pptx
Sequence Diagrams With Pictures (1).pptx
aashrithakondapalli8
 
The-Future-is-Hybrid-Exploring-Azure’s-Role-in-Multi-Cloud-Strategies.pptx
The-Future-is-Hybrid-Exploring-Azure’s-Role-in-Multi-Cloud-Strategies.pptxThe-Future-is-Hybrid-Exploring-Azure’s-Role-in-Multi-Cloud-Strategies.pptx
The-Future-is-Hybrid-Exploring-Azure’s-Role-in-Multi-Cloud-Strategies.pptx
james brownuae
 
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
Surviving a Downturn Making Smarter Portfolio Decisions with OnePlan - Webina...
OnePlan Solutions
 
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World ExamplesMastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
jamescantor38
 
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Eric D. Schabell
 
Buy vs. Build: Unlocking the right path for your training tech
Buy vs. Build: Unlocking the right path for your training techBuy vs. Build: Unlocking the right path for your training tech
Buy vs. Build: Unlocking the right path for your training tech
Rustici Software
 
Digital Twins Software Service in Belfast
Digital Twins Software Service in BelfastDigital Twins Software Service in Belfast
Digital Twins Software Service in Belfast
julia smits
 
Adobe InDesign Crack FREE Download 2025 link
Adobe InDesign Crack FREE Download 2025 linkAdobe InDesign Crack FREE Download 2025 link
Adobe InDesign Crack FREE Download 2025 link
mahmadzubair09
 
Download MathType Crack Version 2025???
Download MathType Crack  Version 2025???Download MathType Crack  Version 2025???
Download MathType Crack Version 2025???
Google
 
Memory Management and Leaks in Postgres from pgext.day 2025
Memory Management and Leaks in Postgres from pgext.day 2025Memory Management and Leaks in Postgres from pgext.day 2025
Memory Management and Leaks in Postgres from pgext.day 2025
Phil Eaton
 
Medical Device Cybersecurity Threat & Risk Scoring
Medical Device Cybersecurity Threat & Risk ScoringMedical Device Cybersecurity Threat & Risk Scoring
Medical Device Cybersecurity Threat & Risk Scoring
ICS
 
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdfTop Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
evrigsolution
 
Troubleshooting JVM Outages – 3 Fortune 500 case studies
Troubleshooting JVM Outages – 3 Fortune 500 case studiesTroubleshooting JVM Outages – 3 Fortune 500 case studies
Troubleshooting JVM Outages – 3 Fortune 500 case studies
Tier1 app
 
How to avoid IT Asset Management mistakes during implementation_PDF.pdf
How to avoid IT Asset Management mistakes during implementation_PDF.pdfHow to avoid IT Asset Management mistakes during implementation_PDF.pdf
How to avoid IT Asset Management mistakes during implementation_PDF.pdf
victordsane
 
Ad

Introduction to PHP_ Lexical structure_Array_Function_String

  • 1. Module 1: Introduction to web techniques- PHP Basics By Mr. Deepak V Ulape (Asst. Professor) College of Management, MIT ADT University, Loni Kalbhor, Pune
  • 2. What is PHP? • PHP is an acronym for "PHP: Hypertext Preprocessor" • PHP is a widely-used, open source scripting language • PHP scripts are executed on the server • PHP is free to download and use PHP files can contain text, HTML, CSS, JavaScript, and PHP code PHP code is executed on the server, and the result is returned to the browser as plain HTML PHP files have extension ".php" What is a PHP File?
  • 3. Features of 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 Why PHP? • PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.) • PHP is compatible with almost all servers used today (Apache, IIS, etc.) • PHP supports a wide range of databases • PHP is free. Download it from the official PHP resource: www.php.net • PHP is easy to learn and runs efficiently on the server side
  • 4. A PHP script is executed on the server, and the plain HTML result is sent back to the browser. Basic PHP Syntax A PHP script can be placed anywhere in the document. A PHP script starts with <?php and ends with ?>: <?php // PHP code goes here ?> The default file extension for PHP files is ".php". A PHP file normally contains HTML tags, and some PHP scripting code.
  • 5. Example A simple .php file with both HTML code and PHP code: <!DOCTYPE html> <html> <body> <h1>My first PHP page</h1> <?php echo "Hello World!"; ?> </body> </html>
  • 6. Lexical structure of PHP 1. Tokens Tokens are the smallest elements in the PHP language. They include: •Identifiers: Names for variables, functions, classes, etc. They start with a letter or underscore and can contain letters, numbers, and underscores. •Example: $myVariable •Keywords: Reserved words with special meaning (e.g., if, else, for, function, class). •Operators: Symbols that represent operations (e.g., +, -, *, /, =). •Literals: Fixed values such as strings, numbers, and booleans. •Example: 'Hello, World!', 42, true •Delimiters: Special characters that separate different elements in the code.
  • 7. 2. Whitespace and Comments Whitespace (spaces, tabs, newlines) is generally ignored but can improve readability. Comments are used to annotate code and are ignored during execution. •Single-line comments: •// This is a comment •# This is also a comment •Multi-line comments: •/* This is a multi-line comment */ 3. Strings Strings can be defined using single quotes (') or double quotes ("). Double-quoted strings support variable interpolation and escape sequences.
  • 8. 4. Variables Variables in PHP start with the dollar sign ($), followed by the variable name. 5. Operators PHP supports a variety of operators: •Arithmetic: +, -, *, /, % •Comparison: ==, ===, !=, !==, <, > •Logical: &&, ||, ! 6. Control Structures PHP has various control structures for flow control: •Conditional Statements: if, else, switch •Loops: for, while, foreach 7. Functions and Classes Functions are defined using the function keyword. Classes use the class keyword and support inheritance and encapsulation. 8. Namespaces Namespaces allow for better organization of code and to avoid name collisions.
  • 9. PHP Arrays : • Arrays in PHP are a type of data structure that allows us to store multiple elements of similar or different data types under a single variable thereby saving us the effort of creating a different variable for every data. • Types of Array in PHP • Indexed or Numeric Arrays • Associative Arrays • Multidimensional Arrays
  • 10. Types of Array in PHP • Indexed or Numeric Arrays: An array with a numeric index where values are stored linearly. • Associative Arrays: An array with a string index where instead of linear storage, each value can be assigned a specific key. • Multidimensional Arrays: An array that contains a single or multiple arrays within it and can be accessed via multiple indices.
  • 11. • Indexed or Numeric Arrays • These type of arrays can be used to store any type of element, but an index is always a number. By default, the index starts at zero. These arrays can be created in two different ways.
  • 12. <?php // One way to create an indexed array $name_one = array("Zack", "Anthony", "Ram", "Salim", "Raghav"); // Accessing the elements directly echo "Accessing the 1st array elements directly:n"; echo $name_one[2], "n"; echo $name_one[0], "n"; echo $name_one[4], "n"; // Second way to create an indexed array $name_two[0] = "ZACK"; $name_two[1] = "ANTHONY"; $name_two[2] = "RAM"; $name_two[3] = "SALIM"; $name_two[4] = "RAGHAV"; // Accessing the elements directly echo "Accessing the 2nd array elements directly:n"; echo $name_two[2], "n"; echo $name_two[0], "n"; echo $name_two[4], "n"; ?>
  • 13. <?php // Creating an indexed array $name_one = array("Zack", "Anthony", "Ram", "Salim", "Raghav"); // One way of Looping through an array using foreach echo "Looping using foreach: n"; foreach ($name_one as $val){ echo $val. "n"; } // count() function is used to count // the number of elements in an array $round = count($name_one); echo "nThe number of elements are $round n"; // Another way to loop through the array using for echo "Looping using for: n"; for($n = 0; $n < $round; $n++){ echo $name_one[$n], "n"; } ?> Ex: traverse an indexed array using loops in PHP.
  • 14. Associative Arrays • These types of arrays are similar to the indexed arrays but instead of linear storage, every value can be assigned with a user-defined key of string type.
  • 15. <?php // One way to create an associative array $name_one = array("Zack"=>"Zara", "Anthony"=>"Any", "Ram"=>"Rani", "Salim"=>"Sara", "Raghav"=>"Ravina"); // Second way to create an associative array $name_two["zack"] = "zara"; $name_two["anthony"] = "any"; $name_two["ram"] = "rani"; $name_two["salim"] = "sara"; $name_two["raghav"] = "ravina"; // Accessing the elements directly echo "Accessing the elements directly:n"; echo $name_two["zack"], "n"; echo $name_two["salim"], "n"; echo $name_two["anthony"], "n"; echo $name_one["Ram"], "n"; echo $name_one["Raghav"], "n"; ?> Examples of Associative Arrays
  • 16. Multidimensional Arrays • Multi-dimensional arrays are such arrays that store another array at each index instead of a single element. In other words, we can define multi-dimensional arrays as an array of arrays. As the name suggests, every element in this array can be an array and they can also hold other sub-arrays within. Arrays or sub-arrays in multidimensional arrays can be accessed using multiple dimensions.
  • 17. <?php // Defining a multidimensional array $favorites = array( array( "name" => "Dave Punk", "mob" => "5689741523", "email" => "davepunk@gmail.com", ), array( "name" => "Monty Smith", "mob" => "2584369721", "email" => "montysmith@gmail.com", ), array( "name" => "John Flinch", "mob" => "9875147536", "email" => "johnflinch@gmail.com", ) ); // Accessing elements echo "Dave Punk email-id is: " . $favorites[0]["email"], "n"; echo "John Flinch mobile number is: " . $favorites[2]["mob"]; ?>
  • 18. Functions: • A function is a block of code written in a program to perform some specific task. • PHP provides us with two major types of functions: • Built-in functions : PHP provides us with huge collection of built-in library functions. These functions are already coded and stored in form of functions. To use those we just need to call them as per our requirement like, var_dump, fopen(), print_r(), gettype() and so on. • User Defined Functions : Apart from the built-in functions, PHP allows us to create our own customised functions called the user- defined functions. Using this we can create our own packages of code and use it wherever necessary by simply calling it.
  • 19. Creating a Function: 1.Any name ending with an open and closed parenthesis is a function. 2.A function name always begins with the keyword function. 3.To call a function we just need to write its name followed by the parenthesis 4.A function name cannot start with a number. It can start with an alphabet or underscore. 5.A function name is not case-sensitive.
  • 20. Syntax: function function_name(){ executable code; } Example: <?php function funcGeek() { echo "This is Geeks for Geeks"; } // Calling the function funcGeek(); ?>
  • 21. Function Parameters or Arguments : The information or variable, within the function’s parenthesis, are called parameters. These are used to hold the values executable during runtime. A user is free to take in as many parameters as he wants, separated with a comma(,) operator. These parameters are used to accept inputs during runtime. While passing the values like during a function call, they are called arguments. An argument is a value passed to a function and a parameter is used to hold those arguments. In common term, both parameter and argument mean the same. We need to keep in mind that for every parameter, we need to pass its corresponding argument.
  • 23. Example: <?php // function along with three parameters function proGeek($num1, $num2, $num3) { $product = $num1 * $num2 * $num3; echo "The product is $product"; } // Calling the function // Passing three arguments proGeek(2, 3, 5); ?>
  • 24. Setting Default Values for Function parameter PHP allows us to set default argument values for function parameters. If we do not pass any argument for a parameter with default value then PHP will use the default set value for this parameter in the function call. Example: <?php // function with default parameter function defGeek($str, $num=12) { echo "$str is $num years old n"; } // Calling the function defGeek("Ram", 15); // In this call, the default value 12 // will be considered defGeek("Adam"); ?>
  • 25. Returning Values from Functions • 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.
  • 26. <?php // function along with three parameters function proGeek($num1, $num2, $num3) { $product = $num1 * $num2 * $num3; return $product; //returning the product } // storing the returned value $retValue = proGeek(2, 3, 5); echo "The product is $retValue"; ?>
  • 27. Parameter passing to Functions • PHP allows us two ways in which an argument can be passed into a function: • Pass by Value: On passing arguments using pass by value, the value of the argument gets changed within a function, but the original value outside the function remains unchanged. That means a duplicate of the original value is passed as an argument. • Pass by Reference: On passing arguments as pass by reference, the original value is passed. Therefore, the original value gets altered. In pass by reference we actually pass the address of the value, where it is stored using ampersand sign(&).
  • 28. <?php // pass by value function valGeek($num) { $num += 2; return $num; } // pass by reference function refGeek(&$num) { $num += 10; return $num; } $n = 10; valGeek($n); echo "The original value is still $n n"; refGeek($n); echo "The original value changes to $n"; ?> Output: The original value is still 10 The original value changes to 20
  • 29. • Variable Functions • A variable function allows you to call a function dynamically by using a variable that contains the function name. • Example of Variable Functions <?php function sayHello($name) { return "Hello, " . $name; } $functionName = 'sayHello'; echo $functionName('Alice'); // Outputs: Hello, Alice ?> In this example, the function sayHello is called using a variable $functionName that holds its name.
  • 30. Anonymous Functions (Closures) • Anonymous functions, or closures, are functions that have no name and can be used as values. They are often used for callback functions or for creating simple functions on the fly. • Example of Anonymous Functions <?php // Defining an anonymous function $square = function($n) { return $n * $n; }; echo $square(4); // Outputs: 16 // Using an anonymous function as a callback $numbers = [1, 2, 3, 4, 5]; $squaredNumbers = array_map(function($n) { return $n * $n; }, print_r($squaredNumbers); // Outputs: Array ( [0] => 1 [1] => 4 [2] => 9 [3] => 16 [4] => 25 ) ?>
  • 31. Anonymous functions Anonymous functions, also known as closures, allow the creation of functions which have no specified name. They are most useful as the value of callback parameters, but they have many other uses. Anonymous functions are implemented using the Closure class. Example: <?php $greet = function($name) { printf("Hello %srn", $name); }; $greet('World'); $greet('PHP'); ?> Exmple #2 Anonymous function variable assignment example
  • 32. 1. echo •Description: Outputs one or more strings. It is not a function, but a language construct, so it can be used without parentheses. •Usage: Fastest way to output data. php <?php echo "Hello, World!"; echo " This is PHP."; // Multiple strings can be concatenated ?> 2. print •Description: Similar to echo, but it behaves like a function and returns 1, so it can be used in expressions. •Usage: Slightly slower than echo, but can be used in more contexts. php <?php print "Hello, World!"; print(" This is PHP."); ?> Printing functions
  • 33. 3. print_r •Useful for printing arrays and objects in a human-readable format. $array = ["apple", "banana", "cherry"]; print_r($array); 4. var_dump •Displays structured information (type and value) about variables, including arrays and objects. $variable = "Hello, World!"; var_dump($variable); $array = ["name" => "Alice", "age" => 30]; var_dump($array);
  • 34. 5. printf •Formats a string according to specified format codes. Similar to C's printf. $name = "Alice"; $age = 30; printf("%s is %d years old.", $name, $age);
  • 35. Php Strings A string is a sequence of characters They are sequences of characters, like "PHP supports string operations". NOTE − Built-in string functions is given in function reference PHP String Functions Following are valid examples of string $string_1 = "This is a string in double quotes"; $string_2 = ‘This is a somewhat longer, singly quoted string’; $string_39 = "This string has thirty-nine characters"; $string_0 = “ "; // a string with zero characters Singly quoted strings are treated almost literally, whereas doubly quoted strings replace variables with their values as well as specially interpreting certain character sequences.
  • 36. <?php $variable = "name"; $literally = 'My $variable will not print!n'; print($literally); print "<br />"; $literally = "My $variable will print!n"; print($literally); ?> • My $variable will not print!n • My name will print!n
  • 37. String Concatenation Operator • To concatenate two string variables together, use the dot (.) operator <?php $string1="Hello Students"; $string2="1234"; echo $string1 . " " . $string2; ?> Output: Hello Students 1234 • If we look at the code above you see that we used the concatenation operator two times. This is because we had to insert a third string. • Between the two string variables we added a string with a single character, an empty space, to separate the two variables.
  • 38. Types of strings • A string literal can be specified in four different ways: • single quoted • double quoted • heredoc syntax • nowdoc syntax
  • 39. Single quoted • The simplest way to specify a string is to enclose it in single quotes (the character '). • To specify a literal single quote, escape it with a backslash (). To specify a literal backslash, double it (). All other instances of backslash will be treated as a literal backslash: this means that the other escape sequences you might be used to, such as r or n, will be output literally as specified rather than having any special meaning. • Note: Unlike the double-quoted and heredoc syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.
  • 40. <?php echo 'this is a simple string'; echo 'You can also have embedded newlines in strings this way as it is okay to do'; // Outputs: Arnold once said: "I'll be back" echo 'Arnold once said: "I'll be back"'; // Outputs: You deleted C:*.*? echo 'You deleted C:*.*?'; // Outputs: You deleted C:*.*? echo 'You deleted C:*.*?'; // Outputs: This will not expand: n a newline echo 'This will not expand: n a newline'; // Outputs: Variables do not $expand $either echo 'Variables do not $expand $either'; ?>
  • 41. Double quoted • Strings that are delimited by double quotes (as in "this") are preprocessed in both the following two ways by PHP − • Certain character sequences beginning with backslash () are replaced with special characters • Variable names (starting with $) are replaced with string representations of their values. • The escape-sequence replacements are − • n is replaced by the newline character • r is replaced by the carriage-return character • t is replaced by the tab character • $ is replaced by the dollar sign itself ($) • " is replaced by a single double-quote (") • is replaced by a single backslash ()
  • 42. Heredoc • A third way to delimit strings is the heredoc syntax: <<<. After this operator, an identifier is provided, then a newline. The string itself follows, and then the same identifier again to close the quotation. • The closing identifier must begin in the first column of the line. Also, the identifier must follow the same naming rules as any other label in PHP: it must contain only alphanumeric characters and underscores, and must start with a non-digit character or underscore. • PHP heredoc strings behave like double-quoted strings, without the double-quotes. It means that they don’t need to escape quotes and expand variables. • When you place variables in a double-quoted string, PHP will expand the variable names. If a string contains the double quotes (“), you need to escape them using the backslash character(). For example:
  • 43. • First, start with the <<< operator, an identifier, and a new line: • <<<IDENTIFIER • Second, specify the string, which can span multiple lines and includes single quotes (‘) or double quotes (“). • Third, close the string with the same identifier. • The identifier must contain only alphanumeric characters and underscores and start with an underscore or a non-digit character. • The closing identifier must follow these rules: • Begins at the first column of the line • Contains no other characters except a semicolon (;). • The character before and after the closing identifier must be a newline character defined by the local operating system.
  • 44. <?php $he = 'Bob’; $she = 'Alice’; $text = "$he said, "PHP is awesome". "Of course." $she agreed."; echo $text; Output: Bob said, "PHP is awesome". "Of course." Alice agreed.
  • 45. Nowdocs • Nowdocs are to single-quoted strings what heredocs are to double- quoted strings. A nowdoc is specified similarly to a heredoc, but no parsing is done inside a nowdoc. The construct is ideal for embedding PHP code or other large blocks of text without the need for escaping. It shares some features in common with the SGML <![CDATA[ ]]> construct, in that it declares a block of text which is not for parsing. • A nowdoc is identified with the same <<< sequence used for heredocs, but the identifier which follows is enclosed in single quotes, e.g. <<<'EOT'. All the rules for heredoc identifiers also apply to nowdoc identifiers, especially those regarding the appearance of the closing identifier.
  • 46. <?php class foo { public $foo; public $bar; function __construct() { $this->foo = 'Foo'; $this->bar = array('Bar1', 'Bar2', 'Bar3'); } } $foo = new foo(); $name = 'MyName'; echo <<<'EOT' My name is "$name". I am printing some $foo->foo. Now, I am printing some {$foo->bar[1]}. This should not print a capital 'A': x41 EOT; ?> The above example will output: My name is "$name". I am printing some $foo->foo. Now, I am printing some {$foo->bar[1]}. This should not print a capital 'A': x41
  • 47. String Manipulation Functions: • String manipulation and searching are fundamental tasks in PHP •Concatenation •Use the . operator to concatenate strings. $string1 = "Hello"; $string2 = "World"; $result = $string1 . " " . $string2; // "Hello World" •String Length •Use strlen() to get the length of a string. $length = strlen($result); // 11
  • 48. •Substring •Use substr() to get a portion of a string. $sub = substr($result, 0, 5); // "Hello" •String Replacement •Use str_replace() to replace occurrences of a substring. $newString = str_replace("World", "PHP", $result); // "Hello PHP“ Changing Case Use strtoupper() and strtolower() for changing case. $upper = strtoupper($result); // "HELLO WORLD“ $lower = strtolower($result); // "hello world"
  • 49. •Trimming Whitespace •Use trim() to remove whitespace from the beginning and end of a string. $trimmed = trim(" Hello World "); // "Hello World" •String Splitting •Use explode() to split a string into an array. $array = explode(" ", $result); // ["Hello", "World"] •Joining Strings •Use implode() to join an array into a string. php $joined = implode(", ", $array); // "Hello, World"
  • 50. String Searching Functions 1.Finding Substring Position •Use strpos() to find the position of a substring. $position = strpos($result, "World"); // 6 2.Finding the Last Occurrence •Use strrpos() to find the last position of a substring. $lastPosition = strrpos($result, "o"); // 7 3.Substring Search (Case Insensitive) •Use stripos() for a case-insensitive search. php $caseInsensitivePosition = stripos($result, "world"); // 6
  • 51. •Checking for Substring •Use str_contains() to check if a string contains a substring (PHP 8.0+). $contains = str_contains($result, "Hello"); // true •Regular Expression Search •Use preg_match() for pattern matching. if (preg_match("/Hello/", $result)) { echo "Found 'Hello'!"; }
  • 52. <?php $text = " Welcome to PHP string manipulation! "; // Trim the text $trimmedText = trim($text); // Replace a word $replacedText = str_replace("PHP", "Python", $trimmedText); // Find position of 'to' $position = strpos($replacedText, "to"); // Change case $upperText = strtoupper($replacedText); // Output results echo "Original: $textn"; echo "Trimmed: $trimmedTextn"; echo "Replaced: $replacedTextn"; echo "Position of 'to': $positionn"; echo "Uppercase: $upperTextn"; ?>
  • 53. String comparison • the string comparison using the equal (==) operator & strcmp() Function in PHP, along with understanding their implementation through the example. • PHP == Operator: The comparison operator called Equal Operator is the double equal sign “==”. This operator accepts two inputs to compare and returns a true value if both of the values are the same (It compares the only value of the variable, not data types) and returns a false value if both of the values are not the same. • This should always be kept in mind that the present equality operator == is different from the assignment operator =. The assignment operator assigns the variable on the left to have a new value as the variable on right, while the equal operator == tests for equality and returns true or false as per the comparison results.
  • 54. <?php // Declaration of strings $name1 = "Geeks"; $name2 = "Geeks"; // Use == operator if ($name1 == $name2) { echo 'Both strings are equal'; } else { echo 'Both strings are not equal'; } ?> Output: Both the strings are equal
  • 55. PHP strcmp() Function: • PHP strcmp() Function: The strcmp() is an inbuilt function in PHP that is used to compare two strings. This function is case-sensitive which points that capital and small cases will be treated differently, during comparison. This function compares two strings and tells whether the first string is greater or smaller or equals the second string. This function is binary-safe string comparison.
  • 56. Syntax: strcmp( $string1, $string2 ) Parameters: This function accepts two parameters as mentioned above and described below: •$string1: This parameter refers to the first string to be used in the comparison. It is a mandatory parameter. •$string2: This parameter refers to the second string to be used in the comparison. It is a mandatory parameter. Return Values: The function returns a random integer value depending on the condition of the match, which is given by: •Returns 0 if the strings are equal. •Returns a negative value (< 0), if $string2 is greater than $string1. •Returns a positive value (> 0) if $string1 is greater than $string2.
  • 57. <?php // Declaration of strings $name1 = "Geeks"; $name2 = "geeks"; // Use strcmp() function if (strcmp($name1, $name2) !== 0) { echo 'Both strings are not equal'; } else { echo 'Both strings are equal'; } ?> Output: Both strings are not equal
  翻译: