0% found this document useful (0 votes)
3 views11 pages

PHP - I UNIT

The document provides an overview of PHP and MySQL, covering basic concepts, syntax, and features of PHP. It includes questions and answers on topics such as PHP installation, data types, variable scope, and embedding PHP in HTML. Additionally, it explains advanced concepts like callbacks, operator associativity, and type juggling.

Uploaded by

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

PHP - I UNIT

The document provides an overview of PHP and MySQL, covering basic concepts, syntax, and features of PHP. It includes questions and answers on topics such as PHP installation, data types, variable scope, and embedding PHP in HTML. Additionally, it explains advanced concepts like callbacks, operator associativity, and type juggling.

Uploaded by

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

PHP & MySQL – I UNIT

2 marks:
1. What does PHP stand for? Give PHP code to display “Hello World”.
PHP stands for “Hypertext Preprocessor”. The PHP code to display “Hello World” is given below:
<?php
echo "Hello World";
?>
2. List any four features of PHP.
• Open Source
• Cross-Platform Compatibility
• Database Integration
• Web Server Support
3. Expand PEAR? What it is?
PEAR stands for "PHP Extension and Application Repository." It is a framework and distribution
system for reusable PHP components. PEAR provides a structured library of code that can be used
to simplify web development tasks, offering standardized code packages for various functionalities,
from database access to authentication.
4. How do you include PHP code in an HTML file? Give example.
You can include PHP code in an HTML file using the <?php ... ?> tags.
Example:
<!DOCTYPE html>
<html>
<body>
<h1>My First PHP Page</h1>
<?php
echo "Hello World!";
?>
</body>
</html>
5. How to use white spaces in PHP? Give example.
Whitespace doesn’t matter in a PHP program. You can spread a statement across any number of
lines, or lump a bunch of statements together on a single line. PHP ignores white spaces in code, so
you can use them for readability.
For example, this statement: add($a, $b, $c);
could just as well be written with more whitespace:
add ($a ,
$b ,
$c ,
);
6. List steps to install and configure PHP in windows.
• Download the PHP zip file from the official website.
• Extract the zip file to a directory (e.g., C:\php).
• Add the PHP directory to the Windows PATH environment variable.
• Configure the php.ini file (e.g., enable necessary extensions).
• Restart the web server (e.g., Apache, IIS).
7. What is lexical structure?
The lexical structure of a programming language is the set of basic rules that define the structure of
tokens, comments, and white spaces. It is the lowest-level syntax of the language and specifies such
things as what variable names look like, what characters are used for comments, and how program
statements are separated from each other.
8. What is constant in php. Give example.
A constant is an identifier for a simple value that cannot be changed during the execution of the
script. To create a constant, use the define() function. For example,
<?php
define("GREETING", "Welcome to PHP!");
echo GREETING;
?>
9. What are different ways of writing comments in PHP? Give example.
• Single-line comment: //
• Multi-line comment: /* ... */
• Shell-style comment: #
Example: <?php
// This is a single-line comment
# This is also a single-line comment
/* This is a multi-line comment
that spans multiple lines */
?>
10. What is the purpose of the echo statement in PHP? Give example.
The echo statement is used to output one or more strings. It is one of the most commonly used
methods for displaying text, variables, and HTML code in PHP scripts.
Example: <?php
echo "Hello World!";
?>
11. What are the main data types supported by PHP?
• String • Integer • Float (Double) • Boolean
• Array • Object • NULL • Resource
12. What are resource data type in PHP?
In PHP, a resource is a special variable, holding a reference to an external resource. Resources are
created and used by special functions within PHP to handle files, database connections, image
canvases, etc. The resource data type is unique in that it is used to represent and manipulate these
external resources.
13. Explain the function used to test whether a value is a resource in php? Give example.
The function is_resource() is used to test whether a value is a resource. This function returns true if
the variable is a resource, and false otherwise. Example:
<?php
$con = mysqli_connect("localhost", "user", "password", "database");
if (is_resource($con)) {
echo "This is a valid resource.";
} else {
echo "This is not a resource.";
} ?>
14. What are call backs? Give example.
A callback is a function that is passed as an argument to another function, which can then call the
callback function during its execution.
Example: $callback = function myCallbackFunction()
{
echo "callback achieved";
}
call_user_func($callback);
15. What is the purpose of phpinfo()?
The PHP function phpinfo() creates an HTML page full of information on how PHP was installed
and is currently configured. This function outputs a large amount of information about the current
state of PHP, including configuration settings, installed extensions, and PHP environment variables.
16. What is variable reference? Give example.
Variable reference means that different variables point to the same data.
Example: <?php
$a = "Hello";
$b = & $a;
$b = "World";
echo $a; // Outputs: World
?>
17. What is static and global scope of variable in PHP?
Static scope: A static variable retains its value between all calls to a function.
Eg: <?php
function test() {
static $count = 0;
$count++;
echo $count;
}
test(); // Outputs: 1
test(); // Outputs: 2
Global scope: A global variable is accessible in any part of the script.
Eg: $a = 3;
function foo()
{
global $a;
echo $a;
}
foo(); // Outputs: 3
18. What is operator associativity? Give example.
Operator associativity determines the order in which operators of the same precedence are
processed. Most operators have left-to-right associativity, meaning they are processed from left to
right. Example: <?php
$a = 10; $b = 5; $c = 2;
$result = $a - $b - $c; // Left-associative: (10 - 5) - 2 = 3
echo $result; // Outputs: 3
?>
19. What are auto increment and auto decrement Operators in PHP? Give example.
Auto increment (++): Increases a variable's value by one.
Auto decrement (--): Decreases a variable's value by one.
Example: <?php
$a = 5;
$a++; // $a is now 6
echo $a; // Outputs: 6
$b = 10;
$b--; // $b is now 9
echo $b; // Outputs: 9
?>
20. How do you declare and initialize a variable in PHP?
You declare and initialize a variable by using the dollar sign $ followed by the variable name and
assignment operator =.
Example: <?php
$variable = "Hello World";
echo $variable; // Outputs: Hello World
?>
21. What is type juggling in php? Write the rules for type juggling in php.
Type juggling refers to PHP's ability to automatically convert a variable from one type to another as
needed. Rules:
Type of first operand Type of second operand Conversion performed
Integer Floating point The integer is converted to a floating-point number.
The string is converted to a number; if the value after
Integer String conversion is a floating-point number, the integer is
converted to a floating-point number.
Floating point String The string is converted to a floating-point number.

22. What is the difference between == and === in PHP?


Equality (==) : If both operands are equal after type juggling, this operator returns true;
otherwise, it returns false.
Identity (===) : If both operands are equal and are of the same type, this operator returns true;
otherwise, it returns false. This operator does not do implicit type casting.
23. What is the difference between binary, and ternary operators?
Binary operator: Operates on two operands (e.g., +, -, *, /).
Ternary operator: Operates on three operands. It's a shorthand for if-else
(e.g., condition? expr1 : expr2).
Example: <?php
$a = 10; $b = 5;
echo $a + $b;
$max = ($a > $b) ? $a : $b; // Ternary operator
echo $max; // Outputs: 10
?>
24. What do you mean by Casting Operators? List any two.
Casting operators are used to explicitly convert a value from one type to another.
i. (int) : Cast to integer.
ii. (float) : Cast to float.
25. How do you define a constant in PHP? Give example.
You define a constant using the define() function or the const keyword.
Example: <?php define ("GREETING", "Welcome to PHP!");
echo GREETING;
?>
26. What is the use of Backtick operator? Give example.
The backtick operator (`…`) is used to execute shell commands directly from PHP.
Example: <?php $output = `ls -l`;
echo $output;
?>
27. What is use of Execution operator? Give example.
The execution operator (backticks) executes the string contained between the backticks as a shell
command and returns the output.
Example: <?php $date = `date`;
echo "Current date and time is: $date";
?>
Long Answer Questions
1. List and explain any four key features of PHP.
Open Source: PHP is free to use and open source, which means it is developed and maintained by a
worldwide community of developers who contribute to its ongoing development and support. This
allows for continuous improvement and extensive documentation.
Cross-Platform Compatibility: PHP is platform-independent, meaning it can run on various
operating systems such as Windows, Linux, macOS, and many UNIX variants. This makes it
versatile and usable in diverse environments.
Database Integration: PHP supports integration with a wide variety of databases, including
MySQL, PostgreSQL, Oracle, SQLite, and many others. This enables developers to build dynamic
and data-driven applications with ease.
Web Server Support: PHP is compatible with almost all web servers used today, including Apache,
Nginx, Microsoft IIS, and more. This allows PHP scripts to be executed on different server setups,
making it a flexible choice for web development.
2. Explain brief history of php 2.0 along with its feature list?
PHP 2.0, also known as PHP/FI 2.0, was released in 1997. This version marked a significant
evolution from its predecessor, PHP/FI (Personal Home Page/Forms Interpreter), developed by
Rasmus Lerdorf. PHP 2.0 introduced many foundational changes that shaped the future of PHP as a
server-side scripting language.
Initially, PHP was a simple set of CGI binaries written in C, intended to track visits to Lerdorf's
online resume. As its popularity grew, Lerdorf rewrote the tool, combining his Personal Home Page
tools with a new scripting language, resulting in PHP/FI 2.0.
Features:
• Improved Syntax and Basic Language Structure
• Built-in Support for Databases
• Form Handling and Server-Side Scripting
• Extensible Architecture
• Basic Error Handling and Debugging
3. Explain how to install and configure PHP in windows.
i. Download PHP: Go to the official PHP website (https://www.php.net/) and download the
Windows binary package.
ii. Extract PHP: Extract the downloaded zip file to a directory, for example, C:\php.
iii. Add PHP to System Path: Add the PHP directory to the Windows PATH environment variable:
• Go to System Properties > Advanced tab > Environment Variables.
• Find the "Path" variable in the "System variables" section, and click "Edit." Add C:\php to the list.
iv. Configure php.ini: Copy php.ini-development to php.ini in the PHP directory. Open php.ini and
configure it as needed (e.g., set extension_dir to C:\php\ext and enable necessary extensions).
v. Test PHP Installation: Open Command Prompt and type php -v to verify the installation.
vi. Configure Web Server: Configure your web server (Apache, Nginx, IIS) to work with PHP by
editing the server configuration files to recognize PHP file extensions and process them using the
PHP executable.

4. Explain How Embedding PHP code within HTML.


PHP code is embedded in HTML using PHP tags. The most common tag is <?php … ?>. Any code
inside these tags will be executed on the server before the HTML is sent to the client's browser.
Example: <!DOCTYPE html>
<html>
<head>
<title>My PHP Page</title>
</head>
<body>
<h1>Welcome to My Website</h1>
<?php
echo "<p>Hello, World! This is PHP embedded in HTML.</p>";
?>
</body>
</html>

The HTML structure remains the same, with a <!DOCTYPE html> declaration, and `html`, `head`,
and `body` tags. Inside the `body` tag, the PHP code is enclosed within <?php ... ?> tags. echo is a
PHP statement used to output text or HTML to the web page. The text inside echo is wrapped in
double quotes and enclosed within HTML paragraph tags <p>. When the server processes this PHP
code, it sends the resulting HTML to the client's browser. The PHP code itself is not visible to the
user, only the HTML output it generates.
5. Explain how to Sending Data to Web browser with code example.
To send data to the web browser, PHP uses the echo or print statements. These commands output
data that the server sends to the client (web browser). The browser receives the HTML content
generated by PHP and renders it for the user.
Example: <?php
header("Content-Type: text/html");
echo "<h1>Data sent to the browser</h1>";
echo "<p>This is a paragraph sent from the server to the browser.</p>";
?>
In this example, header("Content-Type: text/html"); sets the content type to HTML, and the echo
statements send the HTML content to the browser.
6. Explain various scalar data types in PHP with example.
Integer: An integer is a non-decimal number, either positive or negative, including zero. It can be
written in decimal, hexadecimal, or octal format.
Example: <?php
$intVar = 123;
echo $intVar; // Outputs: 123
?>

Float (Double) : A float, also known as a double, is a number with a decimal point or in exponential
form. It represents real numbers.
Example: <?php
$floatVar = 3.14;
echo $floatVar; // Outputs: 3.14
?>

String: A string is a sequence of characters enclosed in single quotes ('') or double quotes (" ").
Strings can contain letters, numbers, and special characters.
Example: <?php
$stringVar = "Hello, PHP!";
echo $stringVar; // Outputs: Hello, PHP!
?>

Boolean: A boolean represents two possible values: true or false. Booleans are often used in
conditional statements to control the flow of the program.
Example: <?php
$boolVar = true;
echo $boolVar; // Outputs: 1 (true is displayed as 1)
?>

7. Explain Compound and special data types in PHP with example.


Compound Data Types
Array: An array is a data structure that can hold multiple values under a single variable name.
Arrays can be indexed or associative.
Example: <?php
$arrayVar = array("apple", "banana", "cherry");
echo $arrayVar[1]; // Outputs: banana
?>

Object: An object is an instance of a class. A class is a blueprint for objects, defining properties and
methods.
Example: <?php
class Fruit {
public $name;
function setName($name) {
$this->name = $name
}
function getName() {
return $this->name;
}
}
$apple = new Fruit();
$apple->setName("Apple");
echo $apple->getName(); // Outputs: Apple
?>
Special Data Types
NULL: The `NULL` data type represents a variable with no value. It is the only value of the
`NULL` type and can be assigned to any variable.
Example: <?php
$nullVar = NULL;
echo $nullVar; // Outputs nothing
?>

Resource: A resource is a special variable that holds a reference to an external resource, such as a
database connection or a file handle. Resources are created and used by specific functions.
Example: <?php
$handle = fopen("file.txt", "r");
if (is_resource($handle)) {
echo "This is a valid resource.";
}
?>

8. Write a note on scope of variables in PHP with examples.


Local Scope: Variables declared inside a function have a local scope. They are accessible only
within the function where they are declared.
Example: <?php function myFunction() {
$localVar = 10; // Local variable
echo $localVar; // Output: 10
}
myFunction();
echo $localVar; // Error: Undefined variable $localVar
?>

Global Scope: Variables declared outside of any function or class have a global scope. They can be
accessed from anywhere in the script, including inside functions and methods.
Example: <?php $globalVar = 20; // Global variable
function myFunction() {
global $globalVar;
echo $globalVar; // Output: 20
}
myFunction();
?>

Static variables: are declared inside functions but retain their values between function calls. They
are accessible only within the function where they are declared.
Example: <?php function myFunction() {
static $staticVar = 0; // Static variable
echo $staticVar;
$static Var++; // Increment the static variable
}
myFunction(); // Output: 0
myFunction(); // Output: 1
myFunction(); // Output: 2
?>
Super Global Scope: Super global variables are built-in variables that are always accessible,
regardless of scope. Examples include $_GET, $_POST, $_SESSION, and $_SERVER.
Example: <?php
echo $_SERVER['PHP_SELF']; // Outputs the filename of the currently executing script
?>

9. Write a note on Garbage collection in PHP.


Garbage collection in PHP is a mechanism for automatic memory management. It helps in freeing
up memory that is no longer in use, which prevents memory leaks and optimizes the performance of
PHP scripts. PHP uses reference counting and copy-on-write to manage memory.
Reference Counting: It is used to track how many references (or pointers) exist for a particular
value or memory location. Each variable in PHP has an associated reference count that indicates
how many variables point to the same value. In addition to reference counting, PHP includes a cycle
collector to handle circular references that occurs when two or more objects reference each other,
preventing their reference count from ever reaching zero.
Copy-on-Write (COW): Copy-on-write is an optimization technique used with reference counting.
It allows multiple variables to share the same value in memory until one of them is modified. Upon
modification, a copy of the original value is made, and the modification is applied to this new copy.

10. Explain any two categories of Operators with example.


Arithmetic Operators: Arithmetic operators are used to perform mathematical operations such as
addition, subtraction, multiplication, division, and modulus.
+ Adds two values.
- Subtracts one value from another.
* Multiplies two values.
/ Divides one value by another.
% Returns the remainder of a division
operation.
Example: <?php
$a = 10;
$b = 5;
echo $a + $b; // Outputs: 15
echo $a - $b; // Outputs: 5
echo $a * $b; // Outputs: 50
echo $a / $b; // Outputs: 2
echo $a % $b; // Outputs: 0
?>

Comparison Operators: Comparison operators are used to compare two values and return a
boolean result indicating whether the comparison is true or false.
== Checks if two values are equal.
!= Checks if two values are not equal.
=== Checks if two values are equal and of the same type.
!== Checks if two values are not equal or not of the same type.
> Checks if one value is greater than another.
< Checks if one value is less than another.
>= Checks if one value is greater than or equal to another.
<= Checks if one value is less than or equal to another.
Example: <?php $a = 10;
$b = 5;
var_dump($a == $b); // Outputs: bool(false)
var_dump($a != $b); // Outputs: bool(true)
var_dump($a > $b); // Outputs: bool(true)
var_dump($a < $b); // Outputs: bool(false)
var_dump($a >= $b); // Outputs: bool(true)
var_dump($a <= $b); // Outputs: bool(false)
?>

11. Write a note on various casting operators.


Casting operators in PHP are used to convert a variable from one data type to another explicitly.
PHP supports several casting operators, including:
(int) or (integer): converts a variable to an integer.
<?php
$var = "10.5";
$intVar = (int)$var;
echo $intVar; // Outputs: 10
?>
(bool) or (boolean): converts a value to a boolean data type.
<?php
$value = "true";
$boolValue = (bool)$value; // $boolValue is now a boolean true
?>
(float), (double), or (real): converts a variable to a floating-point number.
<?php
$var = "10.5";
$floatVar = (float)$var;
echo $floatVar; // Outputs: 10.5
?>
(string): converts a variable to a string.
<?php
$var = 123;
$stringVar = (string)$var;
echo $stringVar; // Outputs: “123”
?>
(array): converts a variable to an array.
<?php
$var = "hello";
$arrayVar = (array)$var;
print_r($arrayVar); // Outputs: Array ( [0] => hello )
?>
(object): converts a variable to an object.
<?php
$var = "hello";
$objectVar = (object)$var;
echo $objectVar->scalar; // Outputs: hello
?>
12. Explain Miscellaneous operators with example?
Error suppression (@): Some operators or functions can generate error messages. This operator
suppresses error messages generated by the expression. For example:
<?php
$file = @file('non_existent_file.txt');
if (!$file) {
echo "Failed to open file.";
}
?>
Execution (`...`): The backtick operator executes the string contained between the backticks as a
shell command and returns the output. For example:
$listing = `ls -ls /tmp`;
echo $listing;
Conditional (? :): The conditional operator is a shorthand way of writing an if-else statement. It
evaluates a condition and returns one of two values depending on whether the condition is true or
false.
Syntax: condition? expr1 : expr2
Example: <?php
$age = 20;
$canVote = ($age >= 18) ? "Yes" : "No";
echo "Can vote: $canVote"; // Output: Can vote: Yes
?>
Type (instanceof): The instanceof operator tests whether a variable is an instantiated object of a
given class or implements an interface.
Example: $a = new Foo;
$isAFoo = $a instanceof Foo; // true
$isABar = $a instanceof Bar; // false

You might also like