0% found this document useful (0 votes)
19 views21 pages

PHP Unit 1 Solved

The document provides a comprehensive overview of PHP and MySQL, covering fundamental concepts, features, and examples of PHP code. It includes topics such as data types, variable scope, operators, and installation instructions for PHP on Windows. Additionally, it explains how to embed PHP in HTML and discusses garbage collection in PHP.

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)
19 views21 pages

PHP Unit 1 Solved

The document provides a comprehensive overview of PHP and MySQL, covering fundamental concepts, features, and examples of PHP code. It includes topics such as data types, variable scope, operators, and installation instructions for PHP on Windows. Additionally, it explains how to embed PHP in HTML and discusses garbage collection in PHP.

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/ 21

UNIT 1 PHP MYSQL:

2 MARKS:
1. What does PHP stand for? Give PHP code to display “Hello World”

Answer:

PHP stands for "Hypertext Preprocessor."

Code:

<?php

echo "Hello World";

?>

2. List any four features of PHP

Answer:

Open Source

Cross-Platform Compatibility

Integration with Various Databases

Support for Various Web Servers

3. Expand PEAR? What is it?

Answer:

PEAR stands for "PHP Extension and Application Repository." It is a framework and
distribution system for reusable PHP components.

4. How do you include PHP code in an HTML file? Give an example

Answer:

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

Answer:

PHP ignores white spaces in code, so you can use them for readability.

Example:

<?php

$variable1 = 5;

$variable2 = 10;

$sum = $variable1 + $variable2;

echo $sum; // Outputs 15

?>

6. List steps to install and configure PHP in Windows

Answer:

Download the PHP zip file from the o icial 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?

Answer:

The lexical structure of a programming language is the set of basic rules that define the
structure of tokens, comments, and white spaces.
8. What is a constant in PHP? Give example

Answer:

A constant is an identifier for a simple value that cannot be changed during the
execution of the script.

Example:

<?php

define("GREETING", "Welcome to PHP!");

echo GREETING;

?>

9. What are di erent ways of writing comments in PHP? Give example

Answer:

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

Answer:

The echo statement is used to output one or more strings.

Example:

<?php

echo "Hello World!";

?>
<?php

echo "Hello World!";

?>

11. What are the main data types supported by PHP?

Answer:

String

Integer

Float (Double)

Boolean

Array

Object

NULL

Resource

12. What are resource data type in PHP?

Answer:

A resource is a special variable, holding a reference to an external resource. It is


typically used for handling files, database connections, and other external data
streams.

13. Explain the function used to test whether a value is a resource in PHP? Give example

Answer:

The function is_resource() is used to test whether a value is a resource.

Example:

<?php

$connection = mysqli_connect("localhost", "user", "password", "database");

if (is_resource($connection)) {

echo "This is a valid resource.";

} else {

echo "This is not a resource.";

}
?>

14. What are callbacks? Give example

Answer:

A callback is a function that is passed as an argument to another function.

Example:

<?php

function my_callback_function() {

echo "Hello World!";

function caller($callback) {

call_user_func($callback);

caller('my_callback_function'); // Outputs: Hello World!

?>

15. What is the purpose of phpinfo()?

Answer:

The phpinfo() 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

Answer:

Variable reference means that di erent 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 a variable in PHP?

Answer:

Static scope: A static variable retains its value between function calls.

Global scope: A global variable is accessible in any part of the script.

Example:

<?php

function testStatic() {

static $count = 0;

$count++;

echo $count;

testStatic(); // 1

testStatic(); // 2

$globalVar = "Global Scope";

function testGlobal() {

global $globalVar;

echo $globalVar;

testGlobal(); // Outputs: Global Scope

?>

18. What is operator associativity? Give example

Answer:

Operator associativity determines the direction in which an expression is evaluated if it


has multiple operators of the same precedence.

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

Answer:

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?

Answer:

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

Answer:

Type juggling refers to PHP's ability to automatically convert a variable from one type to
another as needed.

Rules:

Strings with numeric values are converted to numbers.

If a string contains a valid numeric value, it can be used in arithmetic operations.

Boolean true is converted to 1, and false is converted to 0.

22. What is the di erence between == and === in PHP?

Answer:

==: Equality operator. Checks if the values are equal, after type juggling.

===: Identity operator. Checks if the values are identical and of the same type.

23. What is the di erence between binary and ternary operators?

Answer:

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;

$max = ($a > $b) ? $a : $b; // Ternary operator

echo $max; // Outputs: 10

?>

24. What do you mean by Casting Operators? List any two

Answer:

Casting operators are used to explicitly convert a value from one type to another.

Examples:

(int) or (integer)
(float) or (double) or (real)

Example:

<?php

$number = "10.5";

$integerNumber = (int)$number; // Converts to 10

echo $integerNumber; // Outputs: 10

?>

25. How do you define a constant in PHP? Give example

Answer:

You define a constant using the define() function.

Example:

<?php

define("SITE_NAME", "MyWebsite");

echo SITE_NAME; // Outputs: MyWebsite

?>

26. What is the use of Backtick operator? Give example

Answer:

The backtick operator is used to execute shell commands directly from PHP.

Example:

<?php

$output = `ls -l`;

echo "<pre>$output</pre>";

?>

27. What is the use of execution operator? Give example

Answer:

The execution operator (backticks) allows you to execute shell commands from within
PHP.

Example:
<?php

$result = `whoami`;

echo $result; // Outputs the current username

?>

LONG ANSWERS:

1. List and explain any four key features of PHP

Answer:

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 di erent server
setups, making it a flexible choice for web development.

2. Explain brief history of PHP 2.0 along with its feature list

Answer:

PHP 2.0, released in 1997, marked a significant evolution from its predecessor. It
introduced a new parsing engine, enhancing the performance and functionality of the
language.

Key Features of PHP 2.0:


Introduction of the PHP/FI Parsing Engine:

The new parser, written by Zeev Suraski and Andi Gutmans, improved the execution
speed and expanded the language capabilities.

Support for Basic Web Application Development:

PHP 2.0 enabled developers to build more complex web applications compared to
earlier versions.

Improved Syntax:

Enhanced syntax and better language constructs made coding easier and more
e icient.

Extensibility:

Introduction of an extension API, allowing developers to write their own extensions and
further extend PHP's functionality.

3. Explain how to install and configure PHP in Windows

Answer:

Download PHP:

Go to the o icial PHP website (https://www.php.net/) and download the Windows


binary package.

Extract PHP:

Extract the downloaded zip file to a directory, for example, C:\php.

Add PHP to System Path:

Add the PHP directory to the Windows PATH environment variable:

Open System Properties.

Go to the "Advanced" tab and click on "Environment Variables."

Find the "Path" variable in the "System variables" section, select it, and click "Edit."

Add C:\php to the list.

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).

Test PHP Installation:


Open Command Prompt and type php -v to verify the installation.

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

Answer:

Embedding PHP within HTML allows you to create dynamic web pages that can interact
with the server and display dynamic content.

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>

In this example, the PHP code inside <?php ... ?> tags is executed by the server, and the
result is embedded into the HTML page that is sent to the browser.

5. Explain how to Sending Data to Web browser with code example

Answer:

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).
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

Answer:

Scalar data types in PHP represent single values. The main scalar data types are:

Integer:

Whole numbers without a decimal point.

<?php

$intVar = 123;

echo $intVar; // Outputs: 123

?>

Float (Double):

Numbers with a decimal point.

<?php

$floatVar = 3.14;

echo $floatVar; // Outputs: 3.14

?>

String:

A sequence of characters.

<?php

$stringVar = "Hello, PHP!";

echo $stringVar; // Outputs: Hello, PHP!


?>

Boolean:

Represents two possible values: true or false.

<?php

$boolVar = true;

echo $boolVar; // Outputs: 1 (true is displayed as 1)

?>

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

Answer:

Compound Data Types:

Array:

A collection of values indexed by keys.

<?php

$arrayVar = array("apple", "banana", "cherry");

echo $arrayVar[1]; // Outputs: banana

?>

Object:

Instances of classes containing both data and functions.

<?php

class Fruit {

public $name;

function setName($name) {

$this->name = $name

Object:

Instances of classes containing both data and functions.

<?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:**

1. **NULL:**

- A variable with no value.

```php

<?php

$nullVar = NULL;

echo $nullVar; // Outputs nothing

?>

Resource:

A special variable holding a reference to an external resource (e.g., database


connection).

<?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

Answer:

In PHP, variable scope refers to the context within which a variable is defined and
accessible. The main types of scope are:

Local Scope:

Variables declared within a function are local to that function.

<?php

function localScopeExample() {

$localVar = "I am local";

echo $localVar; // Outputs: I am local

localScopeExample();

// echo $localVar; // Error: Undefined variable $localVar

?>

Global Scope:

Variables declared outside any function have a global scope.

<?php

$globalVar = "I am global";

function globalScopeExample() {

global $globalVar;

echo $globalVar; // Outputs: I am global

globalScopeExample();

?>
Static Scope:

Static variables retain their value between function calls.

<?php

function staticScopeExample() {

static $staticVar = 0;

$staticVar++;

echo $staticVar;

staticScopeExample(); // Outputs: 1

staticScopeExample(); // Outputs: 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.

<?php

echo $_SERVER['PHP_SELF']; // Outputs the filename of the currently executing script

?>

9. Write a note on Garbage collection in PHP

Answer:

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 to keep track of
how many variables reference a particular piece of data. When the reference count
drops to zero, the memory is automatically freed.

In addition to reference counting, PHP includes a cycle collector to handle circular


references, which cannot be managed by reference counting alone. Circular references
occur when two or more objects reference each other, preventing their reference count
from ever reaching zero.

The cycle collector periodically scans for and collects circular references, freeing up
memory used by objects that are no longer accessible.
10. Explain any two categories of Operators with example

Answer:

Arithmetic Operators:

Used to perform common mathematical operations.

<?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:

Used to compare two values.

<?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

Answer:
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):

Casts a variable to an integer.

<?php

$var = "10.5";

$intVar = (int)$var;

echo $intVar; // Outputs: 10

?>

(float), (double), or (real):

Casts a variable to a floating-point number.

<?php

$var = "10.5";

$floatVar = (float)$var;

echo $floatVar; // Outputs: 10.5

?>

(string):

Casts a variable to a string.

<?php

$var = 123;

$stringVar = (string)$var;

echo $stringVar; // Outputs: 123

?>

(array):

Casts a variable to an array.

<?php

$var = "hello";

$arrayVar = (array)$var;
print_r($arrayVar); // Outputs: Array ( [0] => hello )

?>

(object):

Casts a variable to an object.

<?php

$var = "hello";

$objectVar = (object)$var;

echo $objectVar->scalar; // Outputs: hello

?>

12. Explain Miscellaneous operators with example

Answer:

Miscellaneous operators in PHP include:

Execution Operator (backticks):

Used to execute shell commands.

<?php

$output = `ls -l`;

echo "<pre>$output</pre>";

?>

Error Control Operator (@):

 Suppresses error messages generated by the expression.

<?php

$file = @file('non_existent_file.txt');

if (!$file) {

echo "Failed to open file.";

?>

Type Operator (instanceof):

Checks if an object is an instance of a specific class or interface.


<?php

class MyClass {}

$obj = new MyClass();

if ($obj instanceof MyClass) {

echo "obj is an instance of MyClass";

?>

Null Coalescing Operator (??):

Returns its first operand if it exists and is not null; otherwise, it returns its second
operand.

<?php

$name = null;

$defaultName = "Guest";

echo $name ?? $defaultName; // Outputs: Guest

?>

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

You might also like