This document provides an overview of server-side scripting using PHP. It includes 15 questions covering PHP topics like variables, data types, arrays, functions, and form handling. The questions are worth a total of 15 marks and include multiple choice, fill in the blank, true/false, and code writing questions. The document then provides details on PHP including an introduction, how it is well-suited for web development, examples of first PHP code, and explanations of variables, data types, arrays, control structures, functions and comments.
PHP is a server-side scripting language commonly used for web development. This document provides an overview of PHP, including what it is, what it can do, why it's useful, and basic PHP syntax and features like variables, arrays, forms, and functions. It also provides instructions on setting up a local PHP development environment using XAMPP.
The document provides an overview of PHP including:
- PHP is an open source scripting language used for web development. PHP scripts are executed on the server and return HTML to browsers.
- PHP files can contain text, HTML, CSS, JavaScript and PHP code. Common file extensions are .php.
- PHP supports variables, arrays, strings and loops. Arrays can be numeric, associative or multidimensional.
- Functions like include() and require() allow including content from one PHP file into another.
- Control structures like while and do-while loops execute code blocks repeatedly based on conditions.
This document provides an overview of PHP basics including:
- What PHP is and how it works as a server-side scripting language
- The basic structure of PHP files and how PHP code is executed
- Common PHP syntax like variables, data types, operators, conditional statements, loops, arrays, and functions
- How to handle forms and user input with the $_GET, $_POST, and $_REQUEST superglobals
- Examples of basic PHP scripts and code snippets
The document is intended as an introduction to PHP for beginners, covering the essential concepts needed to get started with the language.
PHP is a server-side scripting language that was created by Rasmus Lerdoff in 1994 and released in 1998. Major versions include PHP 3 in 1998, PHP 4 in 2000 which improved speed and reliability, and PHP 5 in 2004 which added improved object-oriented programming support. The latest version is PHP 7.4 released in 2019. PHP is an open source language that is widely used for web development due to its ease of use, flexibility, and built-in support for connecting to databases. It allows placing PHP code into HTML files which is then executed on the server and plain HTML is sent to browsers.
This document discusses PHP functions and arrays. It defines PHP functions as reusable pieces of code that can take arguments and return values. There are built-in and user-defined functions. Arrays allow storing multiple values in a single variable. PHP supports indexed, associative, and multidimensional arrays. Indexed arrays use numeric indexes while associative arrays use named keys. Multidimensional arrays store arrays within other arrays, allowing representation of tabular data. Functions and arrays are fundamental PHP concepts that improve code reuse and organization.
PHP is a server-side scripting language that can be embedded into HTML. It is used to dynamically generate client-side code sent as the HTTP response. PHP code is executed on the web server and allows variables, conditional statements, loops, functions, and arrays to dynamically output content. Key features include PHP tags <?php ?> to delimit PHP code, the echo command to output to the client, and variables that can store different data types and change types throughout a program.
PHP is a server-side scripting language that can be embedded into HTML. It is used to dynamically generate client-side code sent as the HTTP response. PHP code is executed on the web server and allows variables, conditional statements, loops, functions, and arrays to dynamically output content. Key features include PHP tags <?php ?> to delimit PHP code, the echo command to output to the client, and variables that can store different data types and change types throughout a program.
Php classes in mumbai
best Php classes in mumbai with job assistance.
our features are:
expert guidance by it industry professionals
lowest fees of 5000
practical exposure to handle projects
well equiped lab
after course resume writing guidance
PHP / MySQL applications are compatible to all operating systems, support all the popular databases, 100% remotely configurable, perfect for web programming & provide higher performance and speed.
PHP is an HTML-embedded scripting language. Much of its syntax is borrowed from C, Java and Perl with a couple of unique PHP-specific features thrown in. The goal of the language is to allow web developers to write dynamically generated pages quickly.
MySQL is a Relational Database Management System (RDBMS) that uses Structured Query Language (SQL).
PHP is the most popular scripting language for web development. It is free, open source and server-side (the code is executed on the server).
PHP third party tool and plug-in integration such as chat, forum, blog and search engine
The document provides an agenda for a one day PHP workshop. The agenda includes an introduction to PHP, instructions on how to install PHP, and an example getting started with PHP. Some key topics that will be covered are PHP basics like variables, arrays, loops, and functions. The workshop aims to get participants up and running with PHP from start to finish in a single day.
This document provides an overview of PHP and MySQL. It defines PHP as a scripting language commonly used on web servers. It then covers basic PHP syntax, variables, arrays, decision making and loops. It also discusses how to connect PHP to MySQL databases, create tables, insert and update data. Finally, it briefly mentions some PHP frameworks like CodeIgniter and CakePHP.
The document outlines an agenda for a PHP crash course, beginning with an introduction to the speaker's background and qualifications. It then covers the basics of PHP including its history, why it's popular, how to get started, basic syntax and types, variables, constants, expressions, control structures, functions, classes and objects. The document recommends additional advanced PHP topics and reading materials.
The document provides an introduction to PHP including:
- PHP is an open source scripting language especially suited for web development and can be embedded into HTML.
- PHP code is executed on the server, generating HTML which is then sent to the client.
- PHP supports variables, operators, conditional statements, arrays, loops, functions, and forms. Key functions like $_GET and $_POST are used to collect form data submitted via GET and POST methods respectively.
php complete reference with database concepts for beginners is generally useful for those who want to start the career as a php developer. given each and every information right from the scratch to understand for the beginners and students as well. I hope this will help you a lot for the beginners to start the career.
This document provides an introduction to PHP, covering its history, syntax, variables, arrays, operators, control structures, and using external data files. PHP is an open-source scripting language mainly used for web development. It allows embedding code into HTML pages. The document outlines PHP's origins and evolution, how it is parsed by servers, and its basic syntax and programming constructs like if/else statements, loops, and functions. It also discusses working with variables, arrays, and reading/writing external files for dynamic web content.
This document discusses PHP user-defined functions and arrays. It covers defining functions with arguments and default values, as well as different types of arrays - indexed, associative, and multidimensional. Functions allow reusable blocks of code to be called, while arrays allow storing and accessing multiple values using a single variable name. Loops can be used to iterate through array elements.
PHP is a widely-used open source scripting language that can be used to create dynamic web pages. PHP code is executed on the server and generates HTML that is sent to the browser. PHP files have a .php extension and can contain HTML, CSS, JavaScript, and PHP code. PHP can connect to databases, collect form data, generate dynamic content, and more. It runs on many platforms and is compatible with popular web servers. Many large sites like Facebook use PHP due to its capabilities and flexibility.
The document provides an overview of basic PHP syntax and concepts, including:
1. PHP scripting blocks start with <?php and end with ?>. Variables, comments, and code lines must follow certain syntax rules.
2. Variables can store different data types and are declared with a $ sign. Arrays allow storing multiple values in one variable and can be numeric, associative, or multidimensional.
3. Common functions for manipulating strings include concatenation, finding length and position. Switch statements and loops like while are used for conditional logic and repetition.
This document provides an overview of PHP, including what PHP is, how PHP scripts work, embedding PHP in web pages, variables, operators, control structures, arrays, functions, and forms. Some key points covered include:
- PHP is a server-side scripting language commonly used for web development. PHP code is embedded within HTML and executed on the server to produce dynamic web page content.
- PHP scripts typically have a .php file extension and use <?php ?> tags. Code within the tags is executed by the server and the results are returned to the browser.
- Variables, constants, operators, and control structures like if/else statements allow PHP to dynamically output content. Arrays and multid
14 Years of Developing nCine - An Open Source 2D Game FrameworkAngelo Theodorou
A 14-year journey developing nCine, an open-source 2D game framework.
This talk covers its origins, the challenges of staying motivated over the long term, and the hurdles of open-sourcing a personal project while working in the game industry.
Along the way, it’s packed with juicy technical pills to whet the appetite of the most curious developers.
A brief introduction to OpenTelemetry, with a practical example of auto-instrumenting a Java web application with the Grafana stack (Loki, Grafana, Tempo, and Mimir).
More Related Content
Similar to Introduction to PHP_ Lexical structure_Array_Function_String (20)
This document discusses PHP functions and arrays. It defines PHP functions as reusable pieces of code that can take arguments and return values. There are built-in and user-defined functions. Arrays allow storing multiple values in a single variable. PHP supports indexed, associative, and multidimensional arrays. Indexed arrays use numeric indexes while associative arrays use named keys. Multidimensional arrays store arrays within other arrays, allowing representation of tabular data. Functions and arrays are fundamental PHP concepts that improve code reuse and organization.
PHP is a server-side scripting language that can be embedded into HTML. It is used to dynamically generate client-side code sent as the HTTP response. PHP code is executed on the web server and allows variables, conditional statements, loops, functions, and arrays to dynamically output content. Key features include PHP tags <?php ?> to delimit PHP code, the echo command to output to the client, and variables that can store different data types and change types throughout a program.
PHP is a server-side scripting language that can be embedded into HTML. It is used to dynamically generate client-side code sent as the HTTP response. PHP code is executed on the web server and allows variables, conditional statements, loops, functions, and arrays to dynamically output content. Key features include PHP tags <?php ?> to delimit PHP code, the echo command to output to the client, and variables that can store different data types and change types throughout a program.
Php classes in mumbai
best Php classes in mumbai with job assistance.
our features are:
expert guidance by it industry professionals
lowest fees of 5000
practical exposure to handle projects
well equiped lab
after course resume writing guidance
PHP / MySQL applications are compatible to all operating systems, support all the popular databases, 100% remotely configurable, perfect for web programming & provide higher performance and speed.
PHP is an HTML-embedded scripting language. Much of its syntax is borrowed from C, Java and Perl with a couple of unique PHP-specific features thrown in. The goal of the language is to allow web developers to write dynamically generated pages quickly.
MySQL is a Relational Database Management System (RDBMS) that uses Structured Query Language (SQL).
PHP is the most popular scripting language for web development. It is free, open source and server-side (the code is executed on the server).
PHP third party tool and plug-in integration such as chat, forum, blog and search engine
The document provides an agenda for a one day PHP workshop. The agenda includes an introduction to PHP, instructions on how to install PHP, and an example getting started with PHP. Some key topics that will be covered are PHP basics like variables, arrays, loops, and functions. The workshop aims to get participants up and running with PHP from start to finish in a single day.
This document provides an overview of PHP and MySQL. It defines PHP as a scripting language commonly used on web servers. It then covers basic PHP syntax, variables, arrays, decision making and loops. It also discusses how to connect PHP to MySQL databases, create tables, insert and update data. Finally, it briefly mentions some PHP frameworks like CodeIgniter and CakePHP.
The document outlines an agenda for a PHP crash course, beginning with an introduction to the speaker's background and qualifications. It then covers the basics of PHP including its history, why it's popular, how to get started, basic syntax and types, variables, constants, expressions, control structures, functions, classes and objects. The document recommends additional advanced PHP topics and reading materials.
The document provides an introduction to PHP including:
- PHP is an open source scripting language especially suited for web development and can be embedded into HTML.
- PHP code is executed on the server, generating HTML which is then sent to the client.
- PHP supports variables, operators, conditional statements, arrays, loops, functions, and forms. Key functions like $_GET and $_POST are used to collect form data submitted via GET and POST methods respectively.
php complete reference with database concepts for beginners is generally useful for those who want to start the career as a php developer. given each and every information right from the scratch to understand for the beginners and students as well. I hope this will help you a lot for the beginners to start the career.
This document provides an introduction to PHP, covering its history, syntax, variables, arrays, operators, control structures, and using external data files. PHP is an open-source scripting language mainly used for web development. It allows embedding code into HTML pages. The document outlines PHP's origins and evolution, how it is parsed by servers, and its basic syntax and programming constructs like if/else statements, loops, and functions. It also discusses working with variables, arrays, and reading/writing external files for dynamic web content.
This document discusses PHP user-defined functions and arrays. It covers defining functions with arguments and default values, as well as different types of arrays - indexed, associative, and multidimensional. Functions allow reusable blocks of code to be called, while arrays allow storing and accessing multiple values using a single variable name. Loops can be used to iterate through array elements.
PHP is a widely-used open source scripting language that can be used to create dynamic web pages. PHP code is executed on the server and generates HTML that is sent to the browser. PHP files have a .php extension and can contain HTML, CSS, JavaScript, and PHP code. PHP can connect to databases, collect form data, generate dynamic content, and more. It runs on many platforms and is compatible with popular web servers. Many large sites like Facebook use PHP due to its capabilities and flexibility.
The document provides an overview of basic PHP syntax and concepts, including:
1. PHP scripting blocks start with <?php and end with ?>. Variables, comments, and code lines must follow certain syntax rules.
2. Variables can store different data types and are declared with a $ sign. Arrays allow storing multiple values in one variable and can be numeric, associative, or multidimensional.
3. Common functions for manipulating strings include concatenation, finding length and position. Switch statements and loops like while are used for conditional logic and repetition.
This document provides an overview of PHP, including what PHP is, how PHP scripts work, embedding PHP in web pages, variables, operators, control structures, arrays, functions, and forms. Some key points covered include:
- PHP is a server-side scripting language commonly used for web development. PHP code is embedded within HTML and executed on the server to produce dynamic web page content.
- PHP scripts typically have a .php file extension and use <?php ?> tags. Code within the tags is executed by the server and the results are returned to the browser.
- Variables, constants, operators, and control structures like if/else statements allow PHP to dynamically output content. Arrays and multid
14 Years of Developing nCine - An Open Source 2D Game FrameworkAngelo Theodorou
A 14-year journey developing nCine, an open-source 2D game framework.
This talk covers its origins, the challenges of staying motivated over the long term, and the hurdles of open-sourcing a personal project while working in the game industry.
Along the way, it’s packed with juicy technical pills to whet the appetite of the most curious developers.
A brief introduction to OpenTelemetry, with a practical example of auto-instrumenting a Java web application with the Grafana stack (Loki, Grafana, Tempo, and Mimir).
Wondershare PDFelement Pro 11.4.20.3548 Crack Free DownloadPuppy jhon
➡ 🌍📱👉COPY & PASTE LINK👉👉👉 ➤ ➤➤ https://drfiles.net/
Wondershare PDFelement Professional is professional software that can edit PDF files. This digital tool can manipulate elements in PDF documents.
GDG Douglas - Google AI Agents: Your Next Intern?felipeceotto
Presentation done at the GDG Douglas event for June 2025.
A first look at Google's new Agent Development Kit.
Agent Development Kit is a new open-source framework from Google designed to simplify the full stack end-to-end development of agents and multi-agent systems.
Code and No-Code Journeys: The Coverage OverlookApplitools
Explore practical ways to expand visual and functional UI coverage without deep coding or heavy maintenance in this session. Session recording and more info at applitools.com
Bonk coin airdrop_ Everything You Need to Know.pdfHerond Labs
The Bonk airdrop, one of the largest in Solana’s history, distributed 50% of its total supply to community members, significantly boosting its popularity and Solana’s network activity. Below is everything you need to know about the Bonk coin airdrop, including its history, eligibility, how to claim tokens, risks, and current status.
https://blog.herond.org/bonk-coin-airdrop/
Have you upgraded your application from Qt 5 to Qt 6? If so, your QML modules might still be stuck in the old Qt 5 style—technically compatible, but far from optimal. Qt 6 introduces a modernized approach to QML modules that offers better integration with CMake, enhanced maintainability, and significant productivity gains.
In this webinar, we’ll walk you through the benefits of adopting Qt 6 style QML modules and show you how to make the transition. You'll learn how to leverage the new module system to reduce boilerplate, simplify builds, and modernize your application architecture. Whether you're planning a full migration or just exploring what's new, this session will help you get the most out of your move to Qt 6.
Maximizing Business Value with AWS Consulting Services.pdfElena Mia
An overview of how AWS consulting services empower organizations to optimize cloud adoption, enhance security, and drive innovation. Read More: https://www.damcogroup.com/aws-cloud-services/aws-consulting.
FME for Climate Data: Turning Big Data into Actionable InsightsSafe Software
Regional and local governments aim to provide essential services for stormwater management systems. However, rapid urbanization and the increasing impacts of climate change are putting growing pressure on these governments to identify stormwater needs and develop effective plans. To address these challenges, GHD developed an FME solution to process over 20 years of rainfall data from rain gauges and USGS radar datasets. This solution extracts, organizes, and analyzes Next Generation Weather Radar (NEXRAD) big data, validates it with other data sources, and produces Intensity Duration Frequency (IDF) curves and future climate projections tailored to local needs. This presentation will showcase how FME can be leveraged to manage big data and prioritize infrastructure investments.
Join the Denver Marketo User Group, Captello and Integrate as we dive into the best practices, tools, and strategies for maintaining robust, high-performing databases. From managing vendors and automating orchestrations to enriching data for better insights, this session will unpack the key elements that keep your data ecosystem running smoothly—and smartly.
We will hear from Steve Armenti, Twelfth, and Aaron Karpaty, Captello, and Frannie Danzinger, Integrate.
In a tight labor market and tighter economy, PMOs and resource managers must ensure that every team member is focused on the highest-value work. This session explores how AI reshapes resource planning and empowers organizations to forecast capacity, prevent burnout, and balance workloads more effectively, even with shrinking teams.
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentricNatan Silnitsky
At Wix, we revolutionized our platform by making integration events the backbone of our 4,000-microservice ecosystem. By abandoning traditional domain events for standardized Protobuf events through Kafka, we created a universal language powering our entire architecture.
We'll share how our "single-aggregate services" approach—where every CUD operation triggers semantic events—transformed scalability and extensibility, driving efficient event choreography, data lake ingestion, and search indexing.
We'll address our challenges: balancing consistency with modularity, managing event overhead, and solving consumer lag issues. Learn how event-based data prefetches dramatically improved performance while preserving the decoupling that makes our platform infinitely extensible.
Key Takeaways:
- How integration events enabled unprecedented scale and extensibility
- Practical strategies for event-based data prefetching that supercharge performance
- Solutions to common event-driven architecture challenges
- When to break conventional architectural rules for specific contexts
Revolutionize Your Insurance Workflow with Claims Management SoftwareInsurance Tech Services
Claims management software enhances efficiency, accuracy, and satisfaction by automating processes, reducing errors, and speeding up transparent claims handling—building trust and cutting costs. Explore More - https://www.damcogroup.com/insurance/claims-management-software
Insurance policy management software transforms complex, manual insurance operations into streamlined, efficient digital workflows, enhancing productivity, accuracy, customer service, and profitability for insurers. Visit https://www.damcogroup.com/insurance/policy-management-software for more details!
Invited Talk at RAISE 2025: Requirements engineering for AI-powered SoftwarE Workshop co-located with ICSE, the IEEE/ACM International Conference on Software Engineering.
Abstract: Foundation Models (FMs) have shown remarkable capabilities in various natural language tasks. However, their ability to accurately capture stakeholder requirements remains a significant challenge for using FMs for software development. This paper introduces a novel approach that leverages an FM-powered multi-agent system called AlignMind to address this issue. By having a cognitive architecture that enhances FMs with Theory-of-Mind capabilities, our approach considers the mental states and perspectives of software makers. This allows our solution to iteratively clarify the beliefs, desires, and intentions of stakeholders, translating these into a set of refined requirements and a corresponding actionable natural language workflow in the often-overlooked requirements refinement phase of software engineering, which is crucial after initial elicitation. Through a multifaceted evaluation covering 150 diverse use cases, we demonstrate that our approach can accurately capture the intents and requirements of stakeholders, articulating them as both specifications and a step-by-step plan of action. Our findings suggest that the potential for significant improvements in the software development process justifies these investments. Our work lays the groundwork for future innovation in building intent-first development environments, where software makers can seamlessly collaborate with AIs to create software that truly meets their needs.
FME as an Orchestration Tool - Peak of Data & AI 2025Safe Software
Processing huge amounts of data through FME can have performance consequences, but as an orchestration tool, FME is brilliant! We'll take a look at the principles of data gravity, best practices, pros, cons, tips and tricks. And of course all spiced up with relevant examples!
FME as an Orchestration Tool - Peak of Data & AI 2025Safe Software
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.
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.
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