KEMBAR78
UT-I PHP & Mysql | PDF | Php | Parameter (Computer Programming)
0% found this document useful (0 votes)
43 views49 pages

UT-I PHP & Mysql

This document provides an overview of PHP, a server scripting language used for web application development. It covers PHP's features, applications, syntax, data types, operators, and the workflow of PHP in web applications. Additionally, it includes examples and explanations of variables, constants, and various programming concepts related to PHP.

Uploaded by

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

UT-I PHP & Mysql

This document provides an overview of PHP, a server scripting language used for web application development. It covers PHP's features, applications, syntax, data types, operators, and the workflow of PHP in web applications. Additionally, it includes examples and explanations of variables, constants, and various programming concepts related to PHP.

Uploaded by

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

Web Applications Development using PHP &

MYSQL
V Semester
M NAGA V VARA PRASAD, Assistant Professor, CS, BVRC (III Chem)
Introduction to PHP:

PHP is a server scripting language, and is a powerful tool for making dynamic and interactive Web pages.
• PHP is an acronym for “PHP: Hypertext Pre-processor”.
• PHP was created by Rasmus Lerdorf in 1994.
• PHP is a widely-used, open source scripting language.
• PHP scripts are executed on the server.
• PHP is free to download and use.

Uses 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
• You can output HTML, images, PDF files, and even flash movies.
• You can also output any text, such as XHTML and XML.
• 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 Features:

⮚ Performance: Script written in PHP executes much faster then those scripts written in other languages such as JSP & ASP.
⮚ Open Source Software: PHP source code is free available on the web, you can developed all the version of PHP according to
your requirement without paying any cost.
⮚ Platform Independent: PHP is called platform independent because a PHP program can run on different kinds of platform
like Window os, Linux os etc
⮚ Compatibility: PHP is compatible with almost all local servers used today like Apache, IIS etc.
⮚ Object Oriented: PHP also supports object oriented programming structure.
⮚ Interpreted: It uses interpreter and doesn’t require any compiler.
⮚ Embedded: PHP code can be easily embedded within HTML tags and script.
⮚ Security: PHP is a secure language with encrypted technology. It prevent threads and virus attacks.
⮚ Database Connectivity: PHP supports all the leading databases such as MYSQL, SQLite, ODBC, etc.

Applications of PHP:
⮚ Web Development: PHP is widely used for creating dynamic websites and web applications by generating interactive content,
handling user inputs, and interacting with databases.
⮚ Command-Line Scripting: PHP can be used to write command-line scripts for automating repetitive tasks, such as data
processing or system monitoring.
⮚ Game Development: PHP is used for backend logic in browser-based multiplayer games, handling user authentication, scores,
and game state.
⮚ Real-Time Applications: PHP supports real-time applications like chat systems and live updates, typically using AJAX or
Web Sockets.
⮚ File Management: PHP handles file uploads and creates file management systems for organizing and downloading files
PHP File

⮚ PHP Files can contain text, HTML, CSS, JavaScript and PHP code
⮚ PHP code is executed on the server, and the result is sent back to the browser.
⮚ PHP Files have extension “ .php”

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. PHP statements end with a semicolon (;). Below, we have an example of a simple PHP file, with a PHP script that uses a
built-in PHP function "echo" to output the text "Hello World!" on a web page:
Example of PHP:

<!DOCTYPE html>
<html>
<body>
<h1>My First PHP Page</h1>
< ?php
// Use echo to print on console
echo “Hello World!”;
?>
</body>
</html>

Output: My First PHP Page


Hello World!
How to Execute the PHP Program
How to declare Comments in PHP

A comment in PHP code is a line that is not executed as a part of the program. These are non-executable statements.
Types:

• Single line comments


These are given using //comment (or) #comment

• Multiple line comments


These are given using /* comments*/
Working of PHP:

Step 1: User Requests the Page


The user enters a URL into a web browser or clicks on a link, making an HTTP request to the web server.
Step 2: Web Server Receives the Request
The web server (Apache, Nginx, etc.) receives the HTTP request. The request is directed to PHP for processing.
The PHP script located on the server is executed.
Step 3: PHP Processes the Request
The PHP script processes any server-side logic, such as handling form submissions, processing data, or making requests to a
database.
If the PHP script requires database interaction, an SQL query is sent to the database.
Step 4: Database Interaction
The PHP script sends a request to the database (e.g., MySQL) with an SQL query. The database processes the query and sends a
response (results of the query) back to the PHP script.
Step 5: PHP Responds with Dynamic Content
Based on the database response, the PHP script processes and prepares the output (dynamic HTML or other content) that will be
sent back to the user’s browser. This response is returned as an HTTP response to the web browser.
Step 6: Web Browser Receives the Response
The web browser receives the HTTP response, which includes dynamic content generated by PHP. The browser renders the
content on the user’s screen. This is how the PHP workflow operates in web applications, where PHP interacts with a database
and a web server to generate dynamic content for the user.
Building blocks of PHP:

Variable:
Variables are used to store the data values(like int, float, char, etc…). Php is a dynamically typed language. i.e., Php has no data
type declaration.
The value can be assigned to the variable in following manner.
Syntax: $variable_name=value;

Eg: <?php
//Declaring variables
$txt=“Hello World!”;
$number=10;
//Displaying variable values
echo $txt;
echo $number;
?>

Output: Hello World!


10
Naming Conventions for PHP Variables:

• All variables in php start with a $(dollar) sign, followed by the name of the variable.
• A variable name must start with a letter or the underscore character _ .
• A variable name cannot start with a number.
• A variable name in PHP can only contain alpha-numeric characters and underscores( A-z, 0-9, and_ ).
• A variable name cannot contain spaces.
PHP Constants:

• A constant is a name or an identifier for a fixed value.


• A constant value cannot be changed during the execution of the script.
• Constants by default in uppercase.
• Constants are defined using PHP’s define( ) function, which accepts two arguments: the name of the constant, and
its value. Once defined the constant value can be accessed at any time just by referring to its name. Here is a
simple example.
Syntax: define( name, value, case-insensitive)
Eg: <?php
// Defining constant
define("SITE_URL", "https://www.tutorialrepublic.com/");
// Using constant
echo 'Thank you for visiting - ' . SITE_URL;
?>
The output of the above code will be:
Thank you for visiting - https://www.tutorialrepublic.com/
Data Types in Php

Data types in php define the values of variable can hold to store information.
PHP data types are used to hold the different types of data or values.
Php supports 8 primitive data types that can be categorized further in 3 types.
1. Scalar Types/predefined
2. Compound Types/user-defined
3. Special Types.
1. Scalar Types/predefined

It holds only single value. There are 4 scalar data types in PHP.
a. Integer b. Float c. String d. Boolean

a. Integer: Integer means numeric data with a negative or positive sign.


[ … -2,-1,0,1,2 …]
• It holds only whole numbers. Without fractional part or decimal points.
• Integer can be decimal (base 10), octal (base 8), Hexadecimal (base 16).
• The range of an integer must be lie between 2147483648 – 2147483647 .
Eg: <?php
$a=123;
echo $a;

?>
Output: 123

b. Float (or) double: A Floating point number is a number with a decimal point. It can hold decimal point.
0.12, 0.23 etc…
Eg: <?php
$a=1.234;
echo "a=",$a;
?>
Output: a=1.234
c. String: A string is a non-numeric data type. It holds letters, numbers and even special characters.
“Hello World!”
• String values must be either within single quotes (or) in double quotes.
• Integer can be decimal (base 10), octal (base 8), Hexadecimal (base 16).
• The range of an integer must be lie between 2147483648 – 2147483647 .
Eg: <?php
$x= "Helloworld!";
$y= 'Helloworld!';
echo $x;
echo "\n";
echo $y;
?>
Output: Helloworld! Helloworld!

d. Boolean: Booleans are the simplest data type works like switch. It holds only two values i.e., True (1) or False (0)
It is used with conditional statements, if the condition is correct it returns True, otherwise False.

Eg: <?php
// Assign the value TRUE to a variable
$b = true;
echo $b;
?> Output: 1
2. Compound Types/user-defined

It can hold multiple values. There are 2 compound data types in php.
a. array
b. object
a. array: It can store multiple values of same data type in a single variable.
It is useful to aggregate a series of related items.
Eg: <?php
$fruits = array("Apple", "Banana", "Mango");
echo $fruits[0]; // Output: Apple
echo “\n”;
echo $fruits[1]; // Output: Banana
?>
b. object: objects are the instances of user-defined classes that can store both data(properties) and actions(methods).
Eg: <?php // Create an object from class
class Student { $stud1 = new Student();
// Property
public $name; // Set the property
echo $stud1->name = "Rahul";
// Method echo “\n”;
function sayHello() {
echo "Hello, I am a student."; // Use the method
} $stud1->sayHello();
} ?>
Output: Hello, I am a student.
3. Special Types

There are 2 special data types in PHP.


a. resource
b. Null
a. resource: A resource is a special variable holding a reference to an external resource.
Eg: <?php
$x=10; Output: X value=10
$y=$x; Y value=10
echo "X value=",$x;
echo “<br>";
echo "Y value=",$y;
?>
b. Null: Null is a special data type that has only one value: NULL.
A variable of data type NULL is a variable that has no value assigned to it. If a variable is created without a value, it
is
automatically assigned a value of NULL.

Eg: <?php Output: NULL


$a = NULL; string(12) "Hello World!"
var_dump($a);
echo "<br>";
$b = "Hello World!";
//$b = NULL;
var_dump($b);
Operators in php

Operators are used to perform operations, variables and values.


a+b where a & b are operands and + is operator
There are classified into 7 types.
1. Arithmetic operators
2. Assignment operators
3. Comparison operators
4. Incrementing and Decrementing Operators
5. Logical Operators
6. String Operators
7. Array Operators
Eg: Program
<?php
$x = 10;
1. Arithmetic operators: There are 5 arithmetic operators that are used to perform $y = 4;
mathematic operators they are +, -, *, /, % echo($x + $y)."<br>"; // 0utputs: 14
echo($x - $y)."<br>"; // 0utputs: 6
echo($x * $y)."<br>"; // 0utputs: 40
echo($x / $y)."<br>"; // 0utputs: 2.5
echo($x % $y)."<br>"; // 0utputs: 2
?>
Output: 14
6
40
2.5
2
2. Assignment operators

The assignment operators are used to assign values to variables. Eg: Program
<?php
$x = 10;
echo "$x \n"; // Outputs: 10
$x = 20;
$x += 30;
echo "$x \n"; // Outputs: 50
$x = 50;
$x -= 20;
echo "$x \n"; // Outputs: 30
$x = 5;
$x *= 25;
echo "$x \n"; // Outputs: 125
$x = 50;
$x /= 10;
echo "$x \n"; // Outputs: 5
$x = 100;
$x %= 15;
echo "$x\n"; // Outputs: 10
?>
3. Comparison operators

The comparison operators are used to compare two values in Eg: Program
a Boolean fashion. <?php
$x = 25;
$y = 35;
$z = "25";
var_dump($x == $z); // Outputs: boolean true
var_dump($x === $z); // Outputs: boolean false
var_dump($x != $y); // Outputs: boolean true
var_dump($x !== $z); // Outputs: boolean true
var_dump($x < $y); // Outputs: boolean true
var_dump($x > $y); // Outputs: boolean false
var_dump($x <= $y); // Outputs: boolean true
var_dump($x >= $y); // Outputs: boolean false
?>
Output: bool(true)
bool(false)
bool(true)
bool(true)
bool(true)
bool(false)
bool(true)
bool(false)
4. Incrementing and Decrementing Operators: Eg: Program

The increment/decrement operators are used to increment/decrement <?php


a variable’s value. $x = 10;
echo "++$x \n"; // Outputs: 11
echo "$x \n"; // Outputs: 11
$x = 10;
echo "$x++ \n"; // Outputs: 10
echo "$x \n"; // Outputs: 11
$x = 10;
echo "--$x \n"; // Outputs: 9
echo "$x \n"; // Outputs: 9
$x = 10;
echo "$x-- \n"; // Outputs: 10
echo "$x \n"; // Outputs: 9
?>
Output: ++10
10
10++
10
--10
10
10--
10
5. Logical Operators:

The logical operators are typically used to combine conditional statements.

Eg: Program
<?php
$year = 2014;
// Leap years are divisible by 400 or by 4 but not 100
if(($year % 400 == 0) || (($year % 100 != 0) && ($year % 4 == 0)))
{
echo "$year is a leap year.";
}
else
{
echo "$year is not a leap year.";
}
?>
Output: 2014 is not a leap year.
6. String Operators:

There are two operators which are specifically designed for strings.

Eg: Program
<?php
$x = "Hello";
$y = " World!";
echo $x . $y; // Outputs: Hello World!
$x .= $y;
echo $x; // Outputs: Hello World!
?>
Output: Hello.world!
Hello world!
7. Array Operators:

The array operators are used to compare arrays:


Output:

Eg: Program
<?php
$x = array("a" => "Red", "b" => "Green", "c" => "Blue");
$y = array("u" => "Yellow", "v" => "Orange", "w" => "Pink");
$z = $x + $y; // Union of $x and $y
var_dump($z);
var_dump($x == $y); // Outputs: boolean false
var_dump($x === $y); // Outputs: boolean false
var_dump($x != $y); // Outputs: boolean true
var_dump($x <> $y); // Outputs: boolean true
var_dump($x !== $y); // Outputs: boolean true
?>
Flow Control Functions in PHP:

PHP Conditional Statements:


Control Functions are used to control the flow of execution depending upon the specified condition/logic.
• The if statement
• The if...else statement
• The if...elseif....else statement
• The switch...case statement

if statement:
(if) is used to test a condition, if the condition is true, the statements inside if will be executed.
Syntax: if (condition)
Eg: Program
{
<?php
Statements;
$age=20;
}
if ($age>18)
Statement-n;
{
echo “You are eligible for vote”;
Flow Chart:
}
?>

Output: You are eligible for vote


if-else statement:

If the condition is true statements inside, the if block will be executed otherwise else block will be executed.
Syntax: if(condition)
{ Eg: Program
Statement block 1; <?php
} $age=17;
else if ($age>18)
{ {
Statement block2; echo “You are eligible for vote”;
} }
Statement-n else
{
echo “You are not eligible for vote”
Flow Chart:
}
?>

Output: You are not eligible for vote


if...elseif...else Statement:

When a series of decisions are involved, we may have to use more than one if statements in nested as follows.
Syntax:
Flow Chart:
if (condition1)
{
// Code to execute if condition1 is true
}
elseif (condition2)
{
// Code to execute if condition2 is true
}
elseif (condition3)
{
// Code to execute if condition3 is true
}
lse
{
// Code to execute if none of the above
conditions are true
}
Eg: Program

<?php
$score = 92;
if ($score >= 90)
{
echo "Excellent!";
}
elseif ($score >= 80)
{
echo "Good job!";
}
elseif ($score >= 70)
{
echo "You passed.";
}
else
{
echo "Sorry, you did not pass.";
}
?>
Output: Excellent!
switch...case statement :

Php provides a multiple branch selection statement known as switch. This selection statement successively tests the value of an
expression against a list of integer or character constants. When a match is found, the statements associated with that constant
are executed. Flow Chart:
Syntax:switch(expression)
{
case value1: block-1 break;
case value2: block-2 break;
.........
...........
default: default-block break;
}
Statement-x;
Eg: Program
<?php
$today = date("D");
switch($today){
case "Mon":
echo "Today is Monday. Clean your house.";
break;
case "Tue":
echo "Today is Tuesday. Buy some food.";
break;
case "Wed":
echo "Today is Wednesday. Visit a doctor.";
break;
case "Thu":
echo "Today is Thursday. Repair your car.";
break;
case "Fri":
echo "Today is Friday. Party tonight.";
break;
case "Sat":
echo "Today is Saturday. Its movie time.";
break;
case "Sun":
echo "Today is Sunday. Do some rest.";
break;
default:
echo "No information available for that day.";
break;
}
?> Output: Today is Sunday. Do some rest.
PHP Loops:

The process of repeatedly executing a block of statements is known as looping. The statements in the block may be executed
any number of times, from zero to infinite number of times. If a loop continues forever, it is called an infinite loop.
• while Loop
• do...while Loop Eg: Program
• for Loop
<?php
• foreach Loop
$i = 1;
while($i <= 3)
while Loop: {
The while is an entry-controlled loop statement. $i++;
The test condition is evaluated and if the condition is true, then echo "The number is " . $i . "<br>";
the body of the loop is executed. After execution of the body, }
the test condition is once again evaluated and if it is true, ?>
the body is executed once again. This process is repeated until
the test condition returns a false value. Output: The number is 2
Syntax: Initialization; The number is 3
while (test condition)
{
// Code to be executed
//Increment/Decrement
}
Flow Chart:
do...while Loop

do … while loops through a block of code once, and then repeats the loop as along as the specific condition is true.

Syntax: Initialization;
Eg: Program
do
<?php
{
$i = 1;
// Code to be executed
do
//Increment/Decrement
{
$i++;
}while(condition);
echo "The number is " . $i . "<br>";
} while($i <= 5)
Flow Chart:
?>

Output: The number is 2


The number is 3
The number is 4
The number is 5
for Loop
The for loop repeats a block of code until a certain condition is true. It is typically used to execute a block of code for certain
number of times.
The parameters of for loop have following meanings:
1. initialization--It is used to initialize the counter variables, and evaluated once unconditionally before the first execution of the
body of the loop.
2. condition--In the beginning of each iteration, condition is evaluated. If it evaluates to true, the loop continues and the nested
statements are executed. If it evaluates to false, the execution of the loop ends.
3. increment--It updates the loop counter with a new value. It is evaluate at the end of each iteration.

Syntax: for(initialization ; condition ; increment/decrement) Eg: Program


{ <?php
for($i=1; $i<5; $i++)
// Code to be executed; {
} echo "Iteration:",$i,"<br>";
}
Flow Chart: ?>
Output: Iteration:1
Iteration:2
Iteration:3
Iteration:4
foreach Loop
The foreach loop is used to iterate over arrays. Eg1: Program
Syntax: foreach($array as $value) <?php
{ $colors=["red", "green", "blue"];
foreach($colors as $color)
// Code to be executed;
{
} //echo "$color \n";
(or) echo $color,"<br>";
foreach($array as $key=>$value) }
?> Eg2: Program
{
// Code to executed; Output: red <?php
} green $superhero=array(“name”=>“Peter Parker",
blue “gmail”=>“peterparker@gmail.com",
“age”=>18);
foreach($superhero as $key=>$value)
{
echo $key.”:”.$value."<br>";
Flow Chart: }
?>
Output: name:Peter Parker
gmail:peterparker@gmail.com
age:18
Code Blocks
A code block is a group of lines that do something together, and it is written between curly braces { ... }.
We use code blocks with: Technique 2: Mix PHP and HTML (Easier for Large HTML)
• if statements (conditions)
• Loops (for, while) <html>
• Functions <body>
<?php
There are two techniques.
$display_prices = true;
Technique 1: Using print( ) Statements (Simple PHP)
<html>
<body> if ($display_prices) {
<?php ?>
$display_prices = true; <table border="1">
if ($display_prices) {
<tr><td colspan="3">Today's Prices</td></tr>
print "<table border=\"1\">";
print "<tr><td colspan=\"3\">Today's Prices</td></tr>"; <tr><td>14</td><td>32</td><td>71</td></tr>
print "<tr><td>14</td><td>32</td><td>71</td></tr>"; </table>
print "</table>"; <?php
}
?> }
</body> ?>
</html> </body>
Output:
Browser Output

Browser Output
Browser output is what you see on the screen when you open a .php file in a web browser.
PHP code runs on the server, and it sends the result (like HTML or text) to the browser.
Working with Functions

Function in PHP
• A function is a self-contained block of code that performs specific task.
• A large program can be divided into simple blocks functions.
• The main use of functions is code reusability.
• Function code written once can be called any number of times.

TYPES OF FUNCTIONS:
1) PREDEFINED FUNCTIONS: These functions that are prewritten and pretested in the library.
Example: array( ), print( ), var_dump( ), date( ), time( ), etc...
2) USER DEFINED FUNCTIONS: functions which are defined by the users are known as user defined functions.

Syntax for User Defined Function(without Parameters):1


function FUNCTION_NAME( )
Syntax for User Defined Function(with Parameters):2
{
function FUNCTION_NAME($parameter list)
Code to be executed;
{
}
Code to be executed;
}
function – Function definition starts with function keyword
FUNCTION_NAME – Function name followed by parentheses { } with or without parameters.
• A user-defined name and function name starts with letter or underscore but not with number.
• Function name is not case sensitive.
Parameters list – it stores values passed from the calling function.

Eg : Program 1 (Functions without Parameters) Eg : Program 2 (Functions with Parameters)


<?php <?php
// Defining function // Defining function
function sayHai( ) function adding($n1, $n2 )
{ {
echo “Hello My Dears”; $sum=$n1+$n2;
} echo “The Sum of two No’s is:”, $sum;
?> }
?>
Calling functions:
A function defined can be invoked by using function name and parameters. Once the called function is executed, the control
passes back to the calling function.

Syntax: FUNCTION_NAME(parameters);
• PHP provides the option to pass parameters inside a function.
•You can pass as many as parameters your like.
Eg : Program 1
•These parameters work like variables inside your function.
<?php
•Values passed to function are actual arguments.
// Defining function
•Parameters in function definition are formal arguments.
function message( )
{
Eg : Program 2
echo "stay home stay safe";
<?php
}
// Defining function
function getSum($num1, $num2)
// Calling function
{
message( );
?> $sum = $num1 + $num2;
Output: stay home stay safe echo "Sum of the two numbers $num1 and $num2 is : $sum";
}

// Calling function
getSum(10, 20);
?>
Output: Sum of the two numbers $num1 and $num2 is : 30
Returning the values from User- Defined Functions:
A function may or may not return a value. If it returns, it returns only one value.
The return statement is used to return a value to the calling function.

Syntax: return(expression);

Eg : Program 1
<?php
// Defining function
function getSum($num1, $num2)
{
$total = $num1 + $num2;
return $total;
}

// Printing returned value


echo getSum(5, 10);
?>
Output: 15
Variable Scope:
The Scope of a variable is the portion of the program within which it is visible or accessed.
Three types of Scopes
1) Local Variables
2) Global Variables
3) Static Variables ( Saving state between Function calls with the static statement)
1) Local Variables: The Variables declared with in a function are called Local variables. Local variables can’t be accessed outside
that function.
Eg : Program 1
<?php
// Defining function
function test( )
{
$greet = “Hello World!”;
return $greet;
}
test( ) // Hello World!
echo $greet( ); // Generate undefined variable error
?>
Output:
2) Global Variables:

The variables declared outside a function are called global variables.


• To access the global variable with in a function use the global keywords before the variable to refer to the global variable

Eg : Program 1
<?php
$greet = “Hello World!”;
// Defining function
function test( )
{
global $greet;
echo “greet \n”;
}

test( ) // Hello World!


echo “$greet \n”; // Hello World!
?>
Output:
Hello World!
Hello World!
3) Static Variables ( Saving state between Function calls with the static statement):

Static keyword is also used to declare variables in a function, which keep their value after the function has ended.
(or)
Static variables are similar to local variables but after executing the function, the value stored in the variable, remains as tease
till the end of the program

Eg : Program
<?php
// Defining function
function test( )
{
static $x=5;
$y=2;
$x++;
$y++;
echo $x;
echo $y;
}
test( );
test( );
?>
Output: 6
3
7
3
Arguments in functions:

Arguments in functions are the values or variables passed to a Calling function when it is call. These values are used by the
function definition to perform operations or return results.

Eg : Program Parameters
<?php
function sayHello($name)
{
echo "Hello, $name!";
}
sayHello(“Ravi!"); // Output: Hello, Ravi!
sayHello("Suresh!"); // Output: Hello, Suresh!
?>
Output:
Ravi
Suresh Arguments
Types of function arguments:

There are four types.


1) Positional arguments
2) Keyword arguments
3) Default arguments
4) Variable length arguments

5) Positional arguments: When you call a function, the values you pass to it are called arguments.
The position(order) of each value must match the position of the parameters in the function.
Number of parameters must be equal to number of arguments.

Eg:
<?php
function greet($name, $age) {
echo "Hi, I am $name. I am $age years old.";
}
greet(“Ravi", 20);
?>
Output:
Hi, I am Ravi. I am 20 years old.
2) Keyword arguments: Keyword arguments (also called named arguments) let you specify the name of each argument when
calling a function.
a) Clear and easy to read,
b) Flexible (you can change the order),
c) Easier to work with when there are many parameters.
Eg:1
<?php
function introduce($name, $age, $city) {
echo "My name is $name, I am $age years old, and I live in $city.";
}

// Keyword arguments
introduce(age: 25, name: "Ravi", city: "Hyderabad");
?>
Output:
My name is Ravi, I am 25 years old, and I live in Hyderabad.
Eg:2
Mixing Positional and Keyword Arguments.
You can mix them, but keyword arguments must come after positional:
introduce("Ravi", age: 25, city: "Hyderabad"); // ✅ OK
introduce(name: "Ravi", 25, "Hyderabad"); // ❌ Error!
3) Default arguments: If you don’t give a value, PHP will automatically use the default value.
It makes the function optional to pass some values.
Syntax:
function functionName($param1 = default_value) {
// code
}

Eg:1
<?php
function greet($name = "Guest") {
echo "Hello, $name!";
}

greet( ); // Output: Hello, Guest!


greet("Asha"); // Output: Hello, Asha!
?>
If you don’t give a name, it will use "Guest".
Eg:2
Default Must Come Last
function wrong($a = 5, $b) { } // ❌ Error
function correct($a, $b = 5) { } // ✅ OK
4) Variable-length arguments: Sometimes, we don't know how many arguments a user will pass.
Variable-length arguments let a function accept any number of values.

Syntax: using ... (three dots) called the splat operator.


function functionName(...$args) {
// $args is now an array of all arguments
}
Eg:1
<?php
function showFruits(...$fruits) {
foreach ($fruits as $fruit) {
echo $fruit . "<br>";
}
}

showFruits("Apple", "Banana", "Mango");


?>
Output: Apple
Banana
Mango
You can pass any number of arguments!
Channels:

⮚ @smileychiiti - Hema study tutorial


⮚ STUDOCU.COM PDF FILE
⮚ Variables-NS lectures, Hema study tutorial, anuupdates.
⮚ Data Types-Hema study turorial, NS lectures
⮚ Operators – Lab Mug, NS lectures
⮚ Code Blocks and Browser Output—Anuupdates & Chatgpt, @Lasya Tech
⮚ Working with Functions—@Lab Mug & @TutorialsPoint & pdfs
⮚ Variable Scopes -- @btechcsetutorial7264 & Anuupdates.
⮚ Arguments of functions--@NS lectures & Chatgpt

You might also like