Short Answer Questions: 1. Write The Structure of PHP Script With An Example
Short Answer Questions: 1. Write The Structure of PHP Script With An Example
GET POST
1) In case of Get request, only limited In case of post request, large
amount of data can be sent because data is amount of data can be sent
sent in header. because data is sent in body.
2) Get request is not secured because data Post request is secured because
is exposed in URL bar. data is not exposed in URL bar.
3) Get request can be bookmarked. Post request cannot be
bookmarked.
4) Get request is idempotent . It means Post request is non-idempotent.
second request will be ignored until
response of first request is delivered
3. How to define a constant variable in PHP? Give an example
A constant is a name or an identifier for a simple value. A constant value cannot
change during the execution of the script. By default, a constant is case-sensitive. By
convention, constant identifiers are always uppercase. A constant name starts with a
letter or underscore, followed by any number of letters, numbers, or underscores. If
you have defined a constant, it can never be changed or undefined.To define a
constant you have to use define() function and to retrieve the value of a constant, you
have to simply specifying its name. Unlike with variables, you do not need to have a
constant with a $. You can also use the function constant() to read a constant's value if
you wish to obtain the constant's name dynamically.
<?php
define("MINSIZE", 50);
echo MINSIZE;
echo constant("MINSIZE"); // same thing as the previous line
?>
4. Differentiate between the 'BITWISE AND' operator and the 'LOGICAL AND'
operator in PHP
& (Bitwise AND) : This is a binary operator i.e. it works on two operand. Bitwise
AND operator in PHP takes two numbers as operands and does AND on every bit of
two numbers. The result of AND is 1 only if both bits are 1.
Dept of Cse,TKRCET 1
Web technologies PHP
'LOGICAL AND'
The logical and operator ‘&&’ expects its operands to be boolean expressions (either
1 or 0) and returns a boolean value.
5. Write a PHP program to print reverse of any number
<?php
$num = 23456;
$revnum = 0;
while ($num > 1)
{
$rem = $num % 10;
$revnum = ($revnum * 10) + $rem;
$num = ($num / 10);
}
echo "Reverse number of 23456 is: $revnum";
?>
Output:
JAVASCRIPT PHP
Does job for Both Front-end and Back-end. Php is used mostly for Back-end
Purposes only.
Javascript is asynchronous, It doesn’t wait Php is synchronous, It waits for
for Input Output operations. IO operations to execute.
Can be run in browsers and after Node, we Php requires a Server to Run.
can also run it in Command line3. Cannot run without a server.
Js can be combined with HTMl, AJAX and Can be combined with HTML
XML. only.
It is a single threaded language that is It is multi-threaded which means
event-driven which means it never blocks it blocks I/O to carry out multiple
and everything runs concurrently. tasks concurrently.
7. Write about superglobals
In PHP super global is one the variable used to access global variables from
anywhere in the PHP script. PHP Super global variables is accessible inside the same
page that defines it, as well as outside the page. While local variable's scope is within
the page that defines it.
Different types of super global variables are:
• $_GLOBALS.
• $_SERVER.
• $_REQUEST.
• $_GET.
• $_POST.
• $_SESSION.
• $_COOKIE.
• $_FILES.
8. Write a php program to find the factorial of any given number
code:
Method 1: static way
<? php.
$num = 4;
$factorial = 1;
Dept of Cse,TKRCET 2
Web technologies PHP
****
*****
<?php
$a = 45;
$b = 78;
echo "Before swapping:<br><br>";
echo "a =".$a." b=".$b."<br><br>";
// Swapping Logic
$third = $a;
$a = $b;
$b = $third;
echo "After swapping:<br><br>";
echo "a =".$a." b=".$b;
?>
Output:
Before Swapping
a=45 b=78
After Swapping
a=78 b=45
11. Define an Array? Explain about the types of Arrays in PHP with an example
An array is a data structure that stores one or more similar type of values in a single
value. For example if you want to store 100 numbers then instead of defining 100
variables its easy to define an array of 100 length.
There are three different kind of arrays and each array value is accessed using an ID c
which is called array index.
• Numeric array − An array with a numeric index. Values are stored and accessed in
linear fashion.
• Associative array − An array with strings as index. This stores element values in
association with key values rather than in a strict linear index order.
• Multidimensional array − An array containing one or more arrays and values are
accessed using multiple indices
Numeric arrays:These arrays can store numbers, strings and any object but their
index will be represented by numbers. By default array index starts from zero.
• Example
Following is the example showing how to create and access numeric arrays.Here we
have used array() function to create array. This function is explained in function
reference
<html>
<body>
<?php
/* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5);
foreach( $numbers as $value ) {
echo "Value is $value <br />";
}
/* Second method to create array. */
$numbers[0] = "one";
$numbers[1] = "two";
Dept of Cse,TKRCET 4
Web technologies PHP
$numbers[2] = "three";
$numbers[3] = "four";
$numbers[4] = "five";
foreach( $numbers as $value ) {
echo "Value is $value <br />";
}
?>
</body>
</html>
Output:
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
Value is one
Value is two
Value is three
Value is four
Value is five
Associative Arrays
The associative arrays are very similar to numeric arrays in term of functionality but
they are different in terms of their index. Associative array will have their index as
string so that you can establish a strong association between key and values.
To store the salaries of employees in an array, a numerically indexed array would not
be the best choice. Instead, we could use the employees names as the keys in our
associative array, and the value would be their respective salary.
<html>
<body>
<?php
/* First method to associate create array. */
$salaries = array("Hari" => 2000, "raghu" => 1000, "zara" => 500);
echo "Salary of Hari is ". $salaries[' Hari '] . "<br />";
echo "Salary of raghu is ". $salaries[' raghu ']. "<br />";
echo "Salary of zara is ". $salaries['zara']. "<br />";
/* Second method to create array. */
$salaries[' Hari '] = "high";
$salaries['raghu '] = "medium";
$salaries['zara'] = "low";
echo "Salary of Hari is ". $salaries['Ha.ri'] . "<br />";
echo "Salary of raghu is ". $salaries[' raghu ']. "<br />";
echo "Salary of zara is ". $salaries['zara']. "<br />";
?>
</body>
</html>
Output:
Salary of Hari is 2000
Salary of Raghu is 1000
Salary of zara is 500
Salary of Hari is high
Salary of raghu is medium
Salary of zara is low
Dept of Cse,TKRCET 5
Web technologies PHP
Multidimensional Arrays
A multi-dimensional array each element in the main array can also be an array. And
each element in the sub-array can be an array, and so on. Values in the multi-dimensional
array are accessed using multiple index.
Example
In this example we create a two dimensional array to store marks of three students in three
subjects
<html>
<body>
<?php
$marks = array(
"mohammad" => array (
"physics" => 35,
"maths" => 30,
"chemistry" => 39
),
"qadir" => array (
"physics" => 30,
"maths" => 32,
"chemistry" => 29
),
"zara" => array (
"physics" => 31,
"maths" => 22,
"chemistry" => 39
)
);
/* Accessing multi-dimensional array values */
echo "Marks for mohammad in physics : " ;
echo $marks['mohammad']['physics'] . "<br />";
echo "Marks for qadir in maths : ";
echo $marks['qadir']['maths'] . "<br />";
echo "Marks for zara in chemistry : " ;
echo $marks['zara']['chemistry'] . "<br />";
?>
</body></html>
Output:
Marks for mohammad in physics : 35
Marks for qadir in maths : 32
Marks for zara in chemistry : 39
12. Write a Program to read the form data of user registration using php and display
the retrieved data.
<!DOCTYPE HTML>
<html>
<body>
<form action="welcome_get.php" method="get">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
Dept of Cse,TKRCET 6
Web technologies PHP
</form>
</body>
</html>
<html>
<body>
Welcome <?php echo $_GET["name"]; ?><br>
Your email address is: <?php echo $_GET["email"]; ?>
</body>
</html>
OUTPUT:
13. Write Php code to read two values from form and find Area of Triangle and display
the result
<html>
<body>
<form method = "post">
Base: <input type="number" name="base">
<br><br>
Height: <input type="number" name="height"><br>
<input type = "submit" name = "submit" value="Calculate">
</form>
</body>
</html>
<?php
if(isset($_POST['submit']))
{
$base = $_POST['base'];
$height = $_POST['height'];
$area = ($base*$height) / 2;
echo "The area of a triangle with base as $base and height as $height is $area";
}
?>
Dept of Cse,TKRCET 7
Web technologies PHP
OUTPUT:
Variables:
The main way to store information in the middle of a PHP program is by using a variable.
Here are the most important things to know about variables in PHP.
• All variables in PHP are denoted with a leading dollar sign ($).
• The value of a variable is the value of its most recent assignment.
• Variables are assigned with the = operator, with the variable on the left-hand side and
the expression to be evaluated on the right.
• Variables can, but do not need, to be declared before assignment.
• Variables in PHP do not have intrinsic types - a variable does not know in advance
whether it will be used to store a number or a string of characters.
• Variables used before they are assigned have default values.
• PHP does a good job of automatically converting types from one to another when
necessary.
• Arithmetic Operators
• Comparison Operators
• Logical (or Relational) Operators
• Assignment Operators
• Conditional (or ternary) Operators
Lets have a look on all operators one by one.
Arithmetic Operators
There are following arithmetic operators supported by PHP language −Assume variable A
holds 10 and variable B holds 20 then −
Logical Operators
There are following logical operators supported by PHP language
Assume variable A holds 10 and variable B holds 20 then
Operator Description Example
And Called Logical AND operator. If both the operands are true (A and B) is
then condition becomes true. true.
Or Called Logical OR Operator. If any of the two operands are (A or B) is
non zero then condition becomes true. true.
&& Called Logical AND operator. If both the operands are non (A && B) is
zero then condition becomes true. true.
|| Called Logical OR Operator. If any of the two operands are (A || B) is
non zero then condition becomes true. true.
! Called Logical NOT Operator. Use to reverses the logical state !(A && B)
of its operand. If a condition is true then Logical NOT operator is false.
will make false.
Assignment Operators
Conditional Operator
There is one more operator called conditional operator. This first evaluates an expression for
a true or false value and then execute one of the two given statements depending upon the
result of the evaluation. The conditional operator has this syntax −
Operators Categories
All the operators we have discussed above can be categorised into following categories −
Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example,
the multiplication operator has higher precedence than the addition operator −
For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher
precedence than + so it first get multiplied with 3*2 and then adds into 7.
Here operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom. Within an expression, higher precedence operators will be
evaluated first.
Dept of Cse,TKRCET 10
Web technologies PHP
*= /= %=
15. Explain the predefined and user defined functions in PHP with an example
A function is a block of code written in a program to perform some specific task. We can
relate functions in programs to employees in a office in real life for a better
understanding of how functions work. Suppose the boss wants his employee to calculate
the annual budget. So how will this process complete? The employee will take
information about the statics from the boss, performs calculations and calculate the
budget and shows the result to his boss. Functions works in a similar manner. They take
informations as parameter, executes a block of statements or perform operations on this
parameters and returns the result.
Syntax:
function function_name(){
executable code;
}
PHP provides us with two major types of functions:
<?php
if(is_numeric("guru"))
{
echo "true";
}
else
{
echo "false";
}
?>
• 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.
<?php
function funcex()
{
echo "This is example";
}
// Calling the function
funcex();
?>
16. What is PHP session, how session is created and destroyed.
An alternative way to make data accessible across the various pages of an entire
website is to use a PHP Session.A session creates a file in a temporary directory on
the server where registered session variables and their values are stored. This data will
be available to all pages on the site during that visit. A session ends when the user
loses the browser or after leaving the site, the server will terminate the session after a
predetermined period of time, commonly 30 minutes duration.
Dept of Cse,TKRCET 11
Web technologies PHP
<?php
session_start();
if( isset( $_SESSION['counter'] ) ) {
$_SESSION['counter'] += 1;
}else {
$_SESSION['counter'] = 1;
}
$msg = "You have visited this page ". $_SESSION['counter'];
$msg .= "in this session.";
?>
<html>
<head>
<title>Setting up a PHP session</title>
</head>
<body>
<?php echo ( $msg ); ?>
</body>
</html>
Output: You have visited this page 1in this session.
A PHP session can be destroyed by session_destroy() function. This function does not need
any argument and a single call can destroy all the session variables. If you want to destroy a
single session variable then you can use unset() function to unset a session variable.
<?php
unset($_SESSION['counter']);
?>
Here is the call which will destroy all the session variables −
<?php
session_destroy();
?>
17. Write a PHP script to open, close, read and write into a file.
• Opening a file
• Reading a file
• Writing a file
• Closing a file
The PHP fopen() function is used to open a file. It requires two arguments stating first the file
name and then mode in which to operate.
Files modes can be specified as one of the six options in this table.
r:Opens the file for reading only.Places the file pointer at the beginning of the file
r+:Opens the file for reading and writing.Places the file pointer at the beginning of the file.
w:Opens the file for writing only.Places the file pointer at the beginning of the file. and
truncates the file to zero length. If files does notexist then it attempts to create a file.
w+:Opens the file for reading and writing only.Places the file pointer at the beginning of the
file.and truncates the file to zero length. If files does notexist then it attempts to create a file.
a:Opens the file for writing only.Places the file pointer at the end of the file.If files does not
exist then it attempts to create a file.
a+:Opens the file for reading and writing only.Places the file pointer at the end of the file.If
files does not exist then it attempts to create a file
If an attempt to open a file fails then fopen returns a value of false otherwise it returns a file
pointer which is used for further reading or writing to that file.
After making a changes to the opened file it is important to close it with the fclose() function.
The fclose() function requires a file pointer as its argument and then returns true when the
closure succeeds or false if it fails.
Reading a fileOnce a file is opened using fopen() function it can be read with a function
called fread(). This function requires two arguments. These must be the file pointer and the
length of the file expressed in bytes.
The files length can be found using the filesize() function which takes the file name as its
argument and returns the size of the file expressed in bytes.
The following example assigns the content of a text file to a variable then displays those
contents on the web page.
<html>
<head>
<title>Reading a file using PHP</title>
</head>
<body>
<?php
$filename = "tmp.txt";
$file = fopen( $filename, "r" );
Dept of Cse,TKRCET 13
Web technologies PHP
Writing a file
A new file can be written or text can be appended to an existing file using the PHP fwrite()
function. This function requires two arguments specifying a file pointer and the string of data
that is to be written. Optionally a third integer argument can be included to specify the length
of the data to write. If the third argument is included, writing would will stop after the
specified length has been reached.
The following example creates a new text file then writes a short text heading inside it. After
closing this file its existence is confirmed using file_exist() function which takes file name as
an argument
<?php
$filename = "/home/user/guest/newfile.txt";
$file = fopen( $filename, "w" );
if( $file == false ) {
echo ( "Error in opening new file" );
exit();
}
fwrite( $file, "This is a simple test\n" );
fclose( $file );
?>
<html>
<head>
<title>Writing a file using PHP</title>
</head>
<body>
<?php
$filename = "newfile.txt";
$file = fopen( $filename, "r" );
Dept of Cse,TKRCET 14
Web technologies PHP
18. Write a PHP script for uploading a file to the server and display the uploaded files
details
A PHP script can be used with a HTML form to allow users to upload files to the server.
Initially files are uploaded into a temporary directory and then relocated to a target
destination by a PHP script
Information in the phpinfo.php page describes the temporary directory that is used for file
uploads as upload_tmp_dir and the maximum permitted size of files that can be uploaded is
stated as upload_max_filesize. These parameters are set into PHP configuration file php.ini
The process of uploading a file follows these steps −
The user opens the page containing a HTML form featuring a text files, a browse button
and a submit button.
The user clicks the browse button and selects a file to upload from the local PC.
The full path to the selected file appears in the text filed then the user clicks the submit
button.
The selected file is sent to the temporary directory on the server.
The PHP script that was specified as the form handler in the form's action attr ibute
checks that the file has arrived and then copies the file into an intended directory.
The PHP script confirms the success to the user.
As usual when writing files it is necessary for both temporary and final locations to have
permissions set that enable file writing. If either is set to be read-only then process will fail.
An uploaded file could be a text file or image file or any document.
Creating an upload form
The following HTML code below creates an up loader form. This form is having method
attribute set to post and enctype attribute is set to multipart/form-data
There is one global PHP variable called $_FILES. This variable is an associate double
dimension array and keeps all the information related to uploaded file. So if the value
assigned to the input's name attribute in uploading form was file, then PHP would create
following five variables –
$_FILES['file']['tmp_name'] the uploaded file in the temporary dir on the web
server.
Dept of Cse,TKRCET 15
Web technologies PHP
Example: Below example should allow upload images and gives back result as uploaded
file information.
<?php
if(isset($_FILES['image']))
{
$file_name =
$_FILES['image']['name'];
$file_size =$_FILES['image']['size']; $file_type=$_FILES['image']['type'];
}
?>
<html> <body>
<form action="" method="POST"
enctype="multipart/form-data">
<input type="file" name="image" /> <input type="submit"/>
<ul>
<li>Sent file: <?php echo $_FILES['image']['name']; ?>
<li>File size: <?php echo $_FILES['image']['size']; ?>
<li>File type: <?php echo $_FILES['image']['type'] ?>
</ul>
<img src=" <?php echo $_FILES['image']['name']; ?>" height="200"
width="200" />
</form>
</body>
</html
Dept of Cse,TKRCET 16
Web technologies PHP
20. What are the differences between Get and post methods in form submitting. Give
the case where we can use get and we can use post methods
BASIS FOR
COMPARISON GET POST
Parameters are placed
inside URI Body
Dept of Cse,TKRCET 17
Web technologies PHP
21. List the statements that are used to connect PHP with MySQL.
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
In the above example, we have used root as a user but you can use any other user as well.
Any user will be able to perform all the SQL operations, which are allowed to that user.
You can disconnect from the MySQL database any time using the exit command at mysql>
prompt.
mysql> exit
PHP provides mysql_connect() function to open a database connection. This function takes
five parameters and returns a MySQL link identifier on success or FALSE on failure.
Syntax
connection mysql_connect(server,user,passwd,new_link,client_flag);
Sr.No. Parameter & Description
server
1
Optional − The host name running the database server. If not specified, then the
default value will be localhost:3306.
user
2
Optional − The username accessing the database. If not specified, then the default
will be the name of the user that owns the server process.
Dept of Cse,TKRCET 18
Web technologies PHP
passwd
3
Optional − The password of the user accessing the database. If not specified, then
the default will be an empty password.
new_link
4
Optional − If a second call is made to mysql_connect() with the same arguments,
no new connection will be established; instead, the identifier of the already opened
connection will be returned.
client_flags
You can disconnect from the MySQL database anytime using another PHP function
mysql_close(). This function takes a single parameter, which is a connection returned by the
mysql_connect() function.
Syntax
bool mysql_close ( resource $link_identifier );
If a resource is not specified, then the last opened database is closed. This function returns
true if it closes the connection successfully otherwise it returns false.
Example
Try the following example to connect to a MySQL server −
<html>
<head>
<title>Connecting MySQL Server</title>
</head>
<body>
<?php
$dbhost = 'localhost:3306';
$dbuser = 'guest';
$dbpass = 'guest123';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($conn);
?>
</body>
</html>
22. Explain PHP form processing with an example
PHPFormHandling:The following is the process that how to collect user inputs submitted through
a form using the PHP superglobal variables $_GET, $_POST and $_REQUEST.
Dept of Cse,TKRCET 19
Web technologies PHP
Open up the favorite code editor and create a new PHP file. Now type the following code
and save this file as "contact-form.php" in the root directory of your project.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Contact Form</title>
</head>
<body>
<h2>Contact Us</h2>
<p>Please fill in this form and send us.</p>
<form action="process-form.php" method="post">
<p>
<label for="inputName">Name:<sup>*</sup></label>
<input type="text" name="name" id="inputName">
</p>
<p>
<label for="inputEmail">Email:<sup>*</sup></label>
<input type="text" name="email" id="inputEmail">
</p>
<p>
<label for="inputSubject">Subject:</label>
<input type="text" name="subject" id="inputSubject">
</p>
<p>
<label for="inputComment">Message:<sup>*</sup></label>
<textarea name="message" id="inputComment" rows="5" cols="30"></textarea>
</p>
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</form>
</body>
</html>
Dept of Cse,TKRCET 20
Web technologies PHP
Explanation of code
Notice that there are two attributes within the opening <form> tag:
• The action attribute references a PHP file "process-form.php" that receives the data
entered into the form when user submit it by pressing the submit button.
• The method attribute tells the browser to send the form data through POST method.
Rest of the elements inside the form are basic form controls to receive user inputs.
To access the value of a particular form field, you can use the following superglobal
variables. These variables are available in all scopes throughout a script.
Superglobal Description
Contains a list of all the field names and values sent by a form using the get method (i.e.
$_GET
via the URL parameters).
Contains a list of all the field names and values sent by a form using the post method
$_POST
(data will not visible in the URL).
Contains the values of both the $_GET and $_POST variables as well as the values of
$_REQUEST
the $_COOKIE superglobal variable.
When a user submit the above contact form through clicking the submit button, the form data
is sent to the "process-form.php" file on the server for processing. It simply captures the
information submitted by the user and displays it to browser.
Dept of Cse,TKRCET 21
Web technologies PHP
The PHP code of "process-form.php" file will look something like this:
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Contact Form</title>
</head>
<body>
<h1>Thank You</h1>
<p>Here is the information you have submitted:</p>
<ol>
<li><em>Name:</em> <?php echo $_POST["name"]?></li>
<li><em>Email:</em> <?php echo $_POST["email"]?></li>
<li><em>Subject:</em> <?php echo $_POST["subject"]?></li>
<li><em>Message:</em> <?php echo $_POST["message"]?></li>
</ol>
</body>
</html>
The PHP code above is quite simple. Since the form data is sent through the post method, you
can retrieve the value of a particular form field by passing its name to the $_POST
superglobal array, and displays each field value using echo() statement.
In real world we cannot trust the user inputs; you must implement some sort of validation to
filter the user inputs before using them. In the next chapter you will learn how sanitize and
validate this contact form data and send it through the email using PHP.
PHP also allows you to write code that perform different actions based on the results of a
logical or comparative test conditions at run time. This means, you can create test conditions
in the form of expressions that evaluates to either true or false and based on these results
you can perform certain actions.
There are several statements in PHP that you can use to make decisions:
• The if statement
• The if...else statement
• The if...elseif....else statement
• The switch...case statement
The if Statement
The if statement is used to execute a block of code only if the specified condition evaluates to
true. This is the simplest PHP's conditional statements and can be written like:
Dept of Cse,TKRCET 22
Web technologies PHP
if(condition){
//Codetobeexecuted
}
The following example will output "Have a nice weekend!" if the current day is Friday:
Example
<?php
$d = date("D");
if($d == "Fri"){
echo "Have a nice weekend!";
}
?>
You can enhance the decision making process by providing an alternative choice through
adding an else statement to the if statement. The if...else statement allows you to execute one
block of code if the specified condition is evaluates to true and another block of code if it is
evaluates to false. It can be written, like this:
if(condition){
// Code to be executed if condition is true
} else{
// Code to be executed if condition is false
}
The following example will output "Have a nice weekend!" if the current day is Friday,
otherwise it will output "Have a nice day!"
Example
<?php
$d = date("D");
if($d == "Fri"){
echo "Have a nice weekend!";
} else{
echo "Have a nice day!";
}
?>
The if...elseif...else a special statement that is used to combine multiple if...else statements.
if(condition1){
// Code to be executed if condition1 is true
} elseif(condition2){
// Code to be executed if the condition1 is false and condition2 is true
} else{
// Code to be executed if both condition1 and condition2 are false
}
Dept of Cse,TKRCET 23
Web technologies PHP
The following example will output "Have a nice weekend!" if the current day is Friday, and
"Have a nice Sunday!" if the current day is Sunday, otherwise it will output "Have a nice
day!"
Example
<?php
$d = date("D");
if($d == "Fri"){
echo "Have a nice weekend!";
} elseif($d == "Sun"){
echo "Have a nice Sunday!";
} else{
echo "Have a nice day!";
}
?>
The ternary operator provides a shorthand way of writing the if...else statements. The ternary
operator is represented by the question mark (?) symbol and it takes three operands: a
condition to check, a result for true, and a result for false.
Example
<?php
if($age < 18){
echo 'Child'; // Display Child if age is less than 18
} else{
echo 'Adult'; // Display Adult if age is greater than or equal to 18
}
?>
Using the ternary operator the same code could be written in a more compact way:
Example
<?php echo ($age < 18) ? 'Child' : 'Adult'; ?>
The ternary operator in the example above selects the value on the left of the colon (i.e.
'Child') if the condition evaluates to true (i.e. if $age is less than 18), and selects the value on
the right of the colon (i.e. 'Adult') if the condition evaluates to false.Code written using the
ternary operator can be hard to read. However, it provides a great way to write compact if-
else statements.
Dept of Cse,TKRCET 24
Web technologies PHP
Example:
<?php
// Function used for assigning new value to
// $string variable and printing it
function print_string( &$string ) {
$string = "Function hello TKR \n";
// Print $string variable
print( $string );
}
// Driver code
$string = "Global hello TKR \n";
print_string( $string );
print( $string );
?>
Output:
Function hello TKR
Function hello TKR
Dept of Cse,TKRCET 25
Web technologies PHP
Dept of Cse,TKRCET 26