0% found this document useful (0 votes)
153 views

Unit 1 - PHP Question Bank

Unit 1_PHP Question Bank -#PHP #phpnotes #phpquestionbank #bharathidasanuniversity #bharathidasan #BharathidasanUniversity #syllabusphp #phpsyllabus #phpsyllabusbharathidasanuniversity

Uploaded by

Nandhu
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)
153 views

Unit 1 - PHP Question Bank

Unit 1_PHP Question Bank -#PHP #phpnotes #phpquestionbank #bharathidasanuniversity #bharathidasan #BharathidasanUniversity #syllabusphp #phpsyllabus #phpsyllabusbharathidasanuniversity

Uploaded by

Nandhu
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/ 17

Unit-I Programming in PHP ACAS

Unit I-(10 Mark)


1. Essentials of PHP
a. Enter PHP
b. PHP on Internet
c. PHP on local machine
d. Creating a First PHP page
e. Printing some text
f. Echo power
g. Working with variables
h. Creating constants
i. Data types
2. Operators
a. Assignment operators
b. Increment and Decrement Operators
c. PHP String operators
d. Bitwise Operators
e. Execution Operators
f. PHP Operator Precedence
g. Comparison Operators
h. Logical Operators
i. Ternary operator

3. Flow Control
a. If statement
b. Else statement
c. Switch statement
d. Using for Loops
e. While Loops
f. Foreach Loop
g. Skipping Iterations

4. Strings
a. String functions
b. Formatting Text Strings
c. Converting to and from Strings

5. Arrays
a. Arrays Types
b. Modifying the Data in Array
c. Deleting Array Elements
d. PHP Array functions
e. Handling array with loop
f. Sorting Arrays
g. Extracting Data from Arrays

1
Unit-I Programming in PHP ACAS

1.ESSENTIAL PHP
A)ENTER PHP

PHP is a scripting language used for web development,


Enter PHP executed on the server side to generate dynamic web content.

PHP Stands PHP stands for "Hypertext Preprocessor." It's recursive because
For it originally stood for "Personal Home Page."

PHP scripts are executed on web servers, generating HTML


Web Servers and other content to be sent to users' browsers.

Created in 1994 by Rasmus Lerdorf as a set of CGI binaries for


1994 - Rasmus tracking visits to his online resume.

PHP/FI The second version of PHP (PHP/FI 2) was released in 1997,


Version 2 introducing the Zend Engine 1, enhancing performance.

Dynamic Web PHP enables the creation of dynamic web pages, where content
Page changes based on user interactions and data.

JavaScript vs JavaScript is a client-side scripting language, while PHP is


PHP server-side. They handle different aspects of web development.

B)GETTING PHP-PHP ON THE INTERNET


 Internet service providers (ISPs) usually support PHP for web development.
 You can inquire with your ISP's support team to confirm PHP support or try
uploading and running a PHP file on their server.
 Make sure to check the file type you'll be developing and ensure compatibility with
the ISP's PHP support.

 Method  PHP Version

 Command Line  Enter php -v in the command prompt or


Interface (CLI) terminal.

 Create a file with a .php extension (e.g.,


version.php) containing the following code:
<?php phpinfo(); ?>
Open the file in a web browser. The PHP
 Create a PHP file version will be displayed.

2
Aspect Unix/Linux Windows macOS

Unit-I Programming in PHP Pre-


ACAS
installed,
can be
Some versions upgraded
of Unix,linux - via
PHP already Download from package
Download installed. php.net/downloads.php. manager.

Apache
pre-
Use pre- installed,
installed or use
Apache, Internet Information third-party
Web Server Nginx, etc. Services (IIS) servers.

Pre-
installed,
Package or use
manager: sudo Installer package or package
Installation apt install php manual setup. manager.

Edit php.ini
file for Edit
Configuration settings. Edit php.ini file. php.ini file.

Extensions
Install via available
package via
manager or Extensions available for package
Extensions compile. download. manager.

Web Browser
Access Access via localhost or network IP.

GETTING PHP-PHP ON THE LOCAL SYSTEM

C.CREATING YOUR DEVELOPMENT ENVIRONMENT:


Operating File
Notes
System Text Editor / IDE Extension
Vim, nano, CLI editors
Unix/Linux Sublime Text, VS .php like Vim and

3
Unit-I Programming in PHP ACAS

Operating File
Notes
System Text Editor / IDE Extension
Code,(komodo- nano; GUI
Linux) options.

Notepad++, Visual
Notepad++ for
Studio Code, Zend
lightweight,
Studio,
VS Code for
Maguma,komodo
features.
Windows .php
TextMate for
simplicity,
Sublime/VS
Code for
TextMate, Sublime
features.
macOS Text, VS Code .php
VS Code and
Atom are
cross-
platform;
PhpStorm is
Visual Studio
dedicated to
Cross- Code, Atom,
PHP.
Platform PhpStorm .php

D.CREATING A FIRST PHP PAGE:


 Create a new file with a .php extension (e.g., first.php).
 Add PHP tags: <?php at the beginning and ?> at the end.
 Inside the tags, write PHP code, like echo "Hello, World!";.
 Save the file in your web server's document root.
E.RUNNING YOUR FIRST PHP PAGE:
 Start your web server (e.g., Apache, Nginx).
 Open a web browser and go to http://localhost/first.php.
 The PHP code will be executed on the server, and the output will be displayed in
the browser.
F.MIXING HTML AND PHP:
 You can embed PHP code within HTML by using PHP tags.
 For example: <p><?php echo "This is a mixed example."; ?></p>
<!DOCTYPE html>
<html>
<head>
<title>PHP and HTML Example</title>

4
Unit-I Programming in PHP ACAS

</head>
<body>
<h1>Welcome to my website</h1>

<?php
$age = 30;
?>
<p><?php
if ($age >= 18) {
echo "I'm an adult.";
} else {
echo "I'm not yet an adult.";
}
?></p>

<footer>
<?php echo date("Y"); ?> MyWebsite.com
</footer>
</body>
</html>
 This allows you to generate dynamic content within your HTML structure.
G.PRINTING SOME TEXT:
 You can use the echo statement to print text in PHP.
 Example: <?php echo "This is some printed text."; ?>
 The text will be sent from the server to the browser and displayed.
H. PRINTING SOME TEXT:
Put text into php files much as HTML page,put an<h1>header and textinto apage

<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello Welcome!";
?>
</body>
</html>

5
Unit-I Programming in PHP ACAS

Output:

J)MY FIRST PHP PAGE


Hello Welcome!
PHP is Fun!
Hello world!
I'm about to learn PHP!
This string was made with multiple parameters.

K)MORE ECHO POWER:

Php run from command line,in fact simply by using the php command.HTML was
not interpreted as html here,it was simply printed out as plain text.\n control
character ,which php interpret as a newline character.
Eg: echo”welcome\n”; echo”to\n”;
echo”php.”;

L) COMMAND LINE PHP:


 Usage: PHP scripts can be executed directly from the command line interface (CLI)
without the need for a web server or browser.

 Syntax: To run a PHP script from the command line, use the php command followed
by the script's filename. For example: php myscript.php.

 Purpose: Command line PHP is useful for running scripts, performing tasks,
automation, testing, and more without needing a web server.

Here are a few additional points about command line PHP:


 Command Options: You can use various options with the php command, such as -v
to check the PHP version, -r to execute a code snippet, or -a to enter an interactive
PHP shell.
 Interactive Mode: Using the -a option starts an interactive PHP shell, allowing you
to enter and execute PHP code directly in the terminal.
 Built-in Web Server: The -S option followed by a host and port starts a simple PHP
development server for testing purposes.
 Execution: When you run a PHP script from the command line, it's executed using
the PHP CLI interpreter, not a web browser.

6
Unit-I Programming in PHP ACAS

M)ADDING COMMENTS TO PHP CODE


Single-Line Comments: Use // to add a single-line comment. Anything after // on
the same line will be treated as a comment.
// This is a single-line comment
$variable = 10; // This is also a comment
Multi-Line Comments: Enclose your comment within /* and */ to create a multi-
line comment that can span across multiple lines.
/* This is a
multi-line comment
spanning multiple lines */
$name = "John";
/*
$age = 30;
This line is commented out
*/

N) Working with Variables in PHP:

 Variable Declaration: Declare variables using the $ symbol followed by the variable
name. Variable names are case-sensitive and must start with a letter or underscore.

$name = "John";
$age = 30;
Variable Types: PHP is loosely typed, meaning you don't need to explicitly declare variable
types. Types are determined dynamically based on the assigned value. Storing Data in
Variables in PHP:
$string = "Hello";
$number = 42;
$float = 3.14;
$boolean = true;
Concatenation: Combine strings and variables using the concatenation operator (.).
$name = "Alice";
$greeting = "Hello, " . $name . "!";

7
Unit-I Programming in PHP ACAS

Interpolation: Variables within double-quoted strings are interpolated, meaning their values
are automatically inserted.
$color = "blue";
echo "The sky is $color.";
O)Creating Constants

O.Creating Constants in PHP:

 Using define():
define("PI", 3.14159);
define("GREETING", "Hello, world!");
Using const (Available in PHP 5.3 and later):
const PI = 3.14159;
const GREETING = "Hello, world!";

Constants have a few characteristics:

 They are case-sensitive.


 They cannot be redefined or unset once defined.
 They are automatically global and can be accessed from any scope.
 By convention, constant names are usually in uppercase.

Constants are helpful for storing values that shouldn't change during the execution of your
script, such as mathematical constants, configuration settings, or messages that need to
remain consistent.
P)DATA TYPE

Data
Type Description Example

Integer Whole numbers without decimal points. $age = 25;

Float Numbers with decimal points. $price = 19.99;

String Sequences of characters (text). $name = "John";

Boolean Represents true or false values. $isStudent = true;

Ordered collection of values, possibly with


Array keys. $fruits = ["apple", "banana", "orange"];

$person = new Person(); $person->name


Object Instances of user-defined classes. = "Alice";

8
Unit-I Programming in PHP ACAS

Data
Type Description Example

Reference to an external resource (e.g.,


Resource file). $file = fopen("file.txt", "r");

Represents an unassigned or undefined


Null value. $emptyValue = null;

Anonymous function capturing $add = function($a, $b) { return $a + $b;


Closure surrounding variables. };

Callable Represents a callable function or method. $func = "myFunction";

Iterable Represents data that can be iterated over. $array = [1, 2, 3];

2)OPERATORS

Operator Type Operator Explanation Example

Assigns a value to a
= variable. $x = 5;

Performs an operation and


Assignment +=, -= and assigns the result to a $y += 3; // Equivalent to $y = $y
Operators others variable. + 3;

Increment and
Decrement Increase or decrease the
Operators ++ and -- value of a variable by 1. $a++; // $a becomes 11

$greeting = "Hello, "; $name =


PHP String "John"; $message = $greeting .
Operators . Concatenates two strings. $name;

Perform operations on individual


Bitwise Operators &, ` , ^` and others bits of integer values.

Execution Executes a shell command $output = ls -l; // Executes "ls -


Operators ` and returns the output. l"

==, !=, ===, Compares values or


Comparison !==, <, >, <=, expressions and returns a $a == $b; // false<br>$a <= $c; //
Operators >= Boolean result. true

Logical Operators && (AND), ` (OR),!` (NOT)

9
Unit-I Programming in PHP ACAS

Operator Type Operator Explanation Example

Provides a shorthand for $age = 18;<br>$message = ($age


Ternary Operator ? : if-else statements. >= 18) ? "Adult" : "Minor";

Arithmetic Perform basic arithmetic $sum = 5 + 3;<br>$product = 4


Operators +, -, *, /, % operations. * 2;

3)FLOW CONTROL

low Control
Structure Definition Syntax Example

Executes a block of code if (condition) { code to $x = 10; if ($x > 5) { echo


if Statement if a condition is true. execute; } "Greater than 5"; }

Executes one block of if (condition) { code to $x = 3; if ($x > 5) { echo


if-else code if a condition is true, execute; } else { code to "Greater than 5"; } else { echo
Statement and another if it's false. execute; } "Less than or equal to 5"; }

$day = "Monday"; switch


($day) { case "Monday":
Evaluates a variable switch (variable) { case echo "Start of the week"; break;
against multiple possible value: code to execute; case "Friday": echo "End of the
switch values and executes break; ... default: code to week"; break; default: echo
Statement corresponding code. execute; } "Somewhere in between"; }

Executes a block of code


repeatedly while a while (condition) { code $i = 0; while ($i < 5) { echo $i;
while Loop condition is true. to execute; } $i++; }

Executes a block of code


at least once, then
do-while repeatedly while a do { code to execute; } php $i = 0; do { echo $i; $i++;
Loop condition is true. while (condition); } while ($i < 5);

Executes a block of code for (initialization;


for a specific number of condition; increment) { for ($i = 0; $i < 5; $i++) { echo
for Loop times. code to execute; } $i; }

$fruits = array("apple",
foreach ($array as "banana", "orange"); foreach
foreach Iterates over elements in $value) { code to ($fruits as $fruit) { echo $fruit;
Loop an array or collection. execute; } }

These flow control structures allow you to control the execution of your PHP code based on
conditions, loops, and iterations, making your programs more dynamic and flexible.

10
Unit-I Programming in PHP ACAS

4) Strings in PHP:

a. String Functions: String functions in PHP provide a wide range of capabilities for
manipulating and working with text strings.

 strlen($string): Returns the length of a string.


 strpos($haystack, $needle): Returns the position of the first occurrence of a
substring in a string.
 substr($string, $start, $length): Returns a portion of a string starting from the
specified position.
 str_replace($search, $replace, $string): Replaces occurrences of a substring with
another string.
 strtolower($string): Converts a string to lowercase.
 strtoupper($string): Converts a string to uppercase.
 trim($string): Removes whitespace from the beginning and end of a string.
 implode($glue, $array): Joins array elements into a string using a specified
separator.
 explode($delimiter, $string): Splits a string into an array of substrings using a
specified delimiter.

b. Formatting Text Strings: Formatting functions help modify and format text strings
according to specific patterns.

 sprintf($format, ...$args): Returns a formatted string using placeholders and values.


 number_format($number, $decimals, $decimalSeparator,
$thousandsSeparator): Formats a number with specified decimal and thousands
separators.

c. Converting to and from Strings: In PHP, you can convert other data types to strings and
vice versa.

 strval($value): Converts a value to a string explicitly.


 (string) $value: Casts a value to a string.
 intval($string): Converts a string to an integer.
 floatval($string): Converts a string to a floating-point number.
 boolval($string): Converts a string to a boolean.

Strings are a fundamental aspect of programming, allowing you to work with textual data in
various ways. PHP's extensive string functions empower you to manipulate and format text to
meet your specific requirements.
String Functions:
$string = "Hello, World";

$length = strlen($string); // Returns: 13


$position = strpos($string, "World"); // Returns: 7

11
Unit-I Programming in PHP ACAS

$substring = substr($string, 0, 5); // Returns: "Hello"


$replaced = str_replace("Hello", "Hi", $string); // Returns: "Hi, World"
$lowercase = strtolower($string); // Returns: "hello, world"
$uppercase = strtoupper($string); // Returns: "HELLO, WORLD"
$trimmed = trim(" This is a sentence "); // Returns: "This is a sentence"
$fruits = array("apple", "banana", "orange");
$joined = implode(", ", $fruits); // Returns: "apple, banana, orange"
$exploded = explode(" ", "This is a sentence"); // Returns: ["This", "is", "a", "sentence"]
b. Formatting Text Strings:
$number = 1234567.89;
$formatted = number_format($number, 2, ".", ","); // Returns: "1,234,567.89"
$formattedString = sprintf("The formatted number is: %s", $formatted); // Returns: "The
formatted number is: 1,234,567.89"
c. Converting to and from Strings:
$value = 42;
$stringValue = strval($value); // Converts integer to string
$intValue = intval($stringValue); // Converts string to integer
5.ARRAYS

Arrays in PHP:

a. Array Types: Arrays in PHP are used to store multiple values in a single variable. There
are three main types of arrays:

 Indexed Arrays: Arrays with numeric keys.


 Associative Arrays: Arrays with named keys.
 Multidimensional Arrays: Arrays containing other arrays.

b. Modifying the Data in Array: You can modify array elements by directly assigning
values to specific keys.

$colors = array("red", "green", "blue");


$colors[1] = "yellow"; // Modifies the element at index 1
c. Deleting Array Elements: You can delete array elements using the unset() function.
$fruits = array("apple", "banana", "orange");
unset($fruits[1]); // Deletes the element at index 1

12
Unit-I Programming in PHP ACAS

d. PHP Array Functions: PHP provides various built-in functions for working with arrays,
like count(), array_push(), array_pop(), array_merge(), and more.

e. Handling Array with Loop: You can iterate through arrays using loops, such as for,
foreach, and while.

$numbers = array(1, 2, 3, 4, 5);


foreach ($numbers as $number) {
echo $number;
}
f. Sorting Arrays: Arrays can be sorted using functions like sort(), rsort(), asort(), and
ksort().
$numbers = array(3, 1, 4, 1, 5, 9, 2);
sort($numbers); // Sorts in ascending order
g. Extracting Data from Arrays: You can extract data from arrays using functions like
array_slice(), array_splice(), and array_chunk()
$fruits = array("apple", "banana", "orange", "grape");
$subset = array_slice($fruits, 1, 2); // Returns ["banana", "orange"]

Arrays are versatile data structures in PHP that allow you to store, manipulate, and organize
multiple values efficiently. Understanding arrays and their various functions is crucial for
effective data management in your PHP programs.

Array Type Definition Example

php $fruits = array("apple", "banana",


Indexed Arrays Arrays with numeric keys. "orange");

php $person = array("name" => "John", "age"


Associative Arrays Arrays with named keys. => 30);

Multidimensional Arrays containing other php $matrix = array(array(1, 2, 3), array(4, 5,


Arrays arrays. 6));
Indexed Arrays:
Indexed arrays, also known as numeric arrays, are one of the simplest and most common
types of arrays in PHP. They use numeric indices to access and store values. The indices start
from 0 and increase incrementally for each element.

13
Unit-I Programming in PHP ACAS

Definition: An indexed array is a collection of values, where each value is associated with a
numeric index.
Syntax:
$arrayName = array(value1, value2, value3, ...);
Example:
$fruits = array("apple", "banana", "orange", "grape");

In this example, the array $fruits contains four elements, and each element is associated with
a numeric index: 0, 1, 2, and 3. You can access these elements using their indices, like
$fruits[0] to get "apple".

Accessing Elements: You can access elements of an indexed array using their numeric
indices:

$firstFruit = $fruits[0]; // Gets the first element: "apple"


$secondFruit = $fruits[1]; // Gets the second element: "banana"
Modifying Elements: You can modify elements in an indexed array by assigning new values
to specific indices:
$fruits[2] = "grapefruit"; // Modifies the third element to "grapefruit"
Adding Elements: You can add new elements to an indexed array by specifying a new index:
$firstFruit = $fruits[0]; // Gets the first element: "apple"
$secondFruit = $fruits[1]; // Gets the second element: "banana"
Looping Through Indexed Arrays: You can use loops like for and foreach to iterate
through the elements of an indexed array:
foreach ($fruits as $fruit) {
echo $fruit . " ";
}
// Outputs: apple banana orange grape grapefruit kiwi
Indexed arrays are useful for storing lists of related data and for performing operations on
multiple values. They are a fundamental concept in PHP and are widely used in
programming.
Associative Arrays:
Associative arrays are arrays where each element is associated with a specific key or name.
Unlike indexed arrays, which use numeric indices, associative arrays use these keys to
identify and access their elements. This makes associative arrays suitable for storing and
working with structured data.

14
Unit-I Programming in PHP ACAS

Definition: An associative array is a collection of values, where each value is associated with
a unique key.
Syntax:
$arrayName = array(
"key1" => value1,
"key2" => value2,
"key3" => value3,
// ...
);
Example:
$person = array(
"name" => "John",
"age" => 30,
"occupation" => "Engineer"
);
In this example, the array $person has three elements, each associated with a unique key:
"name", "age", and "occupation". You can access these elements using their respective keys,
like $person["name"] to get "John".

Accessing Elements:
You can access elements of an associative array using their keys:
$name = $person["name"]; // Gets the value associated with the key "name"
$occupation = $person["occupation"]; // Gets the value associated with the key "occupation"
Modifying Elements: You can modify elements in an associative array by assigning new
values to specific keys:
$person["age"] = 31; // Modifies the value associated with the key "age"
Adding Elements:
You can add new elements to an associative array by specifying a new key:
$person["location"] = "New York"; // Adds a new key-value pair for "location"
Looping Through Associative Arrays: You can use the foreach loop to iterate through the
elements of an associative array:
foreach ($person as $key => $value) {

15
Unit-I Programming in PHP ACAS

echo "$key: $value<br>";


}
// Outputs:
// name: John
// age: 31
// occupation: Engineer
// location: New York
Multidimensional Arrays:
A multidimensional array is an array that contains other arrays as its elements. This allows
you to create complex data structures with multiple levels of nesting, such as arrays of arrays.
Multidimensional arrays are useful for representing tabular data, matrices, and hierarchical
information.
Definition: A multidimensional array is an array in which each element can also be an array
itself.
Syntax:
$matrix = array(
array(value11, value12, ...),
array(value21, value22, ...),
// ...
);

Example:

$matrix = array(
array(1, 2, 3),
array(4, 5, 6),
array(7, 8, 9)
);
n this example, the array $matrix is a 2D array containing three arrays, each representing a
row of values. The first array [1, 2, 3] represents the first row, the second array [4, 5, 6]
represents the second row, and so on.
Accessing Elements: You can access elements of a multidimensional array by specifying
both the row and column indices:
$value = $matrix[1][2]; // Gets the value 6 from the second row and third column

16
Unit-I Programming in PHP ACAS

Modifying Elements: You can modify elements in a multidimensional array just like in
regular arrays, by assigning new values to specific indices:
$matrix[0][1] = 10; // Modifies the value at the first row and second column to 10
Adding Elements: You can add new elements to a multidimensional array by appending new
arrays to it:
$matrix[] = array(10, 11, 12); // Adds a new array as a new row
Looping Through Multidimensional Arrays: You can use nested loops to iterate through
the elements of a multidimensional array:
foreach ($matrix as $row) {
foreach ($row as $value) {
echo "$value ";
}
echo "<br>";
}
// Outputs:
// 1 2 3
// 4 5 6
// 7 8 9
// 10 11 12

17

You might also like