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

Ct-1 PHP

The document provides a comprehensive overview of PHP, detailing its advantages, variable scope, data types, and functions such as var_dump(), extract(), and compact(). It also explains loops, constructors, and the differences between various PHP functions and concepts. Additionally, it includes code examples for associative arrays, arithmetic operations, and string manipulation functions.
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)
10 views

Ct-1 PHP

The document provides a comprehensive overview of PHP, detailing its advantages, variable scope, data types, and functions such as var_dump(), extract(), and compact(). It also explains loops, constructors, and the differences between various PHP functions and concepts. Additionally, it includes code examples for associative arrays, arithmetic operations, and string manipulation functions.
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/ 26

Instruction:

●​ Make compulsory borders

Question Bank :
(2marks)
1)List out the advantages of PHP.

1.​ Open-Source: PHP is freely available, reducing development costs.


2.​ Easy to Learn and Use: It has a C-like and Perl-like syntax, making it simple for
beginners.
3.​ Fast and Stable: PHP ensures high performance and stability for web applications.
4.​ Cross-Platform Compatibility: It runs on various operating systems like Windows,
Linux, and macOS.
5.​ Database Support: PHP supports multiple databases, including MySQL, PostgreSQL,
and MongoDB.
6.​ Rich Built-in Libraries: It provides many pre-built functions, reducing the need for
additional coding.
7.​ Pre-Installed in Linux: Many Linux distributions come with PHP pre-installed,
simplifying deployment.
8.​ Strong Community Support: A large developer community provides constant updates,
security patches, and troubleshooting help.

2)Explain variable scope in PHP.

In PHP, variables can be declared anywhere in the script. The scope of a variable defines the
part of the script where it can be accessed and used. PHP supports three types of variable scopes:

1.​ Local Scope:


○​ A variable declared inside a function is local to that function.
○​ It cannot be accessed outside that function.

Example:​

function test() {
$x = 10; // Local variable
echo $x; // Accessible inside the function
}
test();
// echo $x; // Error: Undefined variable

○​
2.​ Global Scope:
○​ A variable declared outside any function has global scope.
○​ It cannot be accessed directly inside functions unless the global keyword is
used.

Example:​

$y = 20; // Global variable

function display() {
global $y; // Accessing global variable inside a function
echo $y;
}
display();

○​
3.​ Static Scope:
○​ Normally, when a function ends, its local variables are destroyed.
○​ Using the static keyword allows the variable to retain its value between
function calls.

Example:​

function counter() {
static $count = 0; // Static variable
$count++;
echo $count . "<br>";
}

counter(); // Outputs 1
counter(); // Outputs 2

○​ counter(); // Outputs 3
3)Explain var_dump() function with example.

The var_dump() function in PHP is used to display detailed information about a variable,
including its data type and value. It works with all data types, including integers, strings,
arrays, and objects, and is mainly used for debugging and checking variable contents during
development.

Syntax:
var_dump(variable);

Example:
$num = 25;
$text = "PHP";
$list = array(10, "Hello", 3.14);

var_dump($num);
var_dump($text);
var_dump($list);

Output:
int(25)
string(3) "PHP"
array(3) { [0]=> int(10) [1]=> string(5) "Hello" [2]=> float(3.14) }

4)What is an Array?write a syntax of array.​

An array in PHP is a special type of variable that can store multiple values under a single name,
making data management easier and more efficient. Instead of declaring multiple variables, an
array helps in grouping related data, simplifying access and operations.

For example, without an array:

$car1 = "Volvo";

$car2 = "BMW";

$car3 = "Toyota";
If there were hundreds of car names, managing them individually would be inefficient. Arrays
solve this problem by allowing multiple values to be stored together and accessed using an index
number.

Syntax:

$array_name = array(value1, value2, value3, ...);

Example:

$cars = array("Volvo", "BMW", "Toyota");

echo $cars[0]; // Outputs: Volvo

Here, $cars[0] refers to the first element of the array.

5)How to create an array?Explain with example.

An array in PHP is a special type of variable that can hold multiple values under a single name.
This makes it easier to manage and access related data efficiently. Instead of declaring separate
variables for each value, an array groups them together, allowing access using index numbers.

In PHP, the array() function is used to create an array. Each value inside the array()
function is called an element and is assigned an index number, starting from 0.

Syntax:
$array_name = array(value1, value2, value3, ...);

●​ $array_name is the name of the array.


●​ array() stores multiple values in a single variable.
●​ The values inside array() are separated by commas.

Example:
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>

Output:
I like Volvo, BMW and Toyota.

6)Explain, i)Extract() ii)Compact()

i) extract() Function in PHP

The extract() function is an inbuilt PHP function that is used to convert an array into
individual variables. It takes an associative array and creates separate variables for each key,
assigning the corresponding values to them. This function is mainly used when working with
dynamic data where variable names are stored as keys in an array.

Syntax:
extract($input_array);

●​ $input_array: The associative array whose keys will be converted into variable
names.

Example:
<?php
$person = array("name" => "John", "age" => 30, "city" => "New York");

extract($person);

echo "Name: $name, Age: $age, City: $city";


?>

Output:
Name: John, Age: 30, City: New York

ii) compact() Function in PHP


The compact() function is an inbuilt PHP function used to create an array from existing
variables. It takes one or more variable names as arguments, retrieves their values, and stores
them in an associative array where the keys are the variable names and the values are the
corresponding variable values. This function is useful when you need to group multiple related
variables into an array dynamically.

Syntax:
compact(var1, var2, ...);

●​ var1, var2, ...: The names of variables to be included in the array.

Example:
<?php
$firstname = "Peter";
$lastname = "Griffin";
$age = 41;

$result = compact("firstname", "lastname", "age");

print_r($result);
?>

Output:
Array ( [firstname] => Peter [lastname] => Griffin [age] => 41 )


7)Explain array_flip() function with example.

array_flip() Function in PHP

The array_flip() function is an inbuilt PHP function that swaps the keys and values of an
array. This means that all keys become values, and all values become keys.

This function is useful when you need to reverse the key-value mapping in an associative array.
However, if duplicate values exist in the array, only the last encountered value will be used as a
key in the flipped array.

Syntax:
array_flip(array);

Example:
<?php
$fruits = array("a" => "Apple", "b" => "Banana", "c" => "Cherry");

$flippedArray = array_flip($fruits);

print_r($flippedArray);
?>

Output:
Array ( [Apple] => a [Banana] => b [Cherry] => c )

8)Describe loops in PHP.

Loops in PHP are used to execute a block of code repeatedly until a specified condition is met.
They help in automating repetitive tasks and improving code efficiency. PHP supports four types
of loops:

1. for Loop

The for loop is used when the number of iterations is known in advance. It consists of three
parts: initialization, condition, and increment/decrement.

Syntax:
for(initialization; condition; increment/decrement) {
// Code to be executed
}

Example:
<?php
for($i = 1; $i <= 5; $i++) {
echo "Number: $i <br>";
}
?>
2. while Loop

The while loop executes a block of code as long as the condition is true. It is useful when the
number of iterations is unknown.

Syntax:
while(condition) {
// Code to be executed
}

Example:
<?php
$x = 1;
while($x <= 3) {
echo "Value: $x <br>";
$x++;
}
?>

3. do...while Loop

The do...while loop is similar to while, but it executes the code at least once before
checking the condition.

Syntax:
do {
// Code to be executed
} while(condition);

Example:
<?php
$y = 1;
do {
echo "Count: $y <br>";
$y++;
} while($y <= 3);
?>

4. foreach Loop (For Arrays)

The foreach loop is specifically designed for iterating through arrays.

Syntax:
foreach($array as $value) {
// Code to be executed
}

Example:
<?php
$colors = array("Red", "Green", "Blue");

foreach($colors as $color) {
echo "Color: $color <br>";
}
?>

9)Write down the rules for declaring PHP variables.

●​ A variable starts with the $ sign, followed by the name of the variable
●​ A variable name must start with a letter or the underscore character
●​ A variable name cannot start with a number
●​ A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and
_)
●​ Variable names are case-sensitive ($age and $AGE are two different variables)
Remember that PHP variable names are case-sensitive!
10)Differentiate between Constructor & Destructor.

11)Differentiate between Implode and Explode function.

12)State the role of constructor.

A constructor in PHP is a special method that is automatically invoked when an object is


created. It is mainly used for initializing object properties and performing setup tasks.
Key Roles of a Constructor:

1.​ Automatic Execution – Runs automatically when an object is instantiated.


2.​ Initializes Properties – Assigns default or dynamic values to class properties.
3.​ Avoids Code Duplication – Reduces repetitive initialization code.
4.​ Supports Parameterized Initialization – Allows passing values during object creation.
5.​ Manages Dependencies – Helps in setting up required configurations like database
connections.
6.​ Ensures Object Readiness – Makes sure that an object is properly initialized before
use.

Syntax:
class Car {
public $brand;

function __construct($brand) {
$this->brand = $brand;
echo "Car object for $brand created!";
}
}

$obj = new Car("Toyota"); // Constructor is called automatically

-------------------------------------------------------------------------------------------------------------------------------
(4marks)
1)Write a program to create associative array in PHP.(CO2/A)

Code:
<?php
// Creating an associative array
$student = array(
"name" => "John",
"age" => 20,
"course" => "Computer Science",
"grade" => "A"
);

// Accessing elements using keys


echo "Student Name: " . $student["name"] . "<br>";
echo "Age: " . $student["age"] . "<br>";
echo "Course: " . $student["course"] . "<br>";
echo "Grade: " . $student["grade"];
?>

Output:

Student Name: John


Age: 20
Course: Computer Science
Grade: A

2)Describe Data types in PHP in detail.(CO1/U)

PHP variables can store different types of data, and each type serves a specific purpose. PHP
supports the following data types:

1. String

A sequence of characters enclosed in single (') or double (") quotes. It is used to store text
values.​
Example:

$text = "Hello, PHP!";


echo $text;

2. Integer

A whole number (positive or negative) without decimals. It is used for counting and calculations.​
Example:

$num = 100;
echo $num;

3. Float (Double)

A number with decimal points or in exponential form. It is used for precise calculations.​
Example:

$price = 99.99;
echo $price;

4. Boolean
Represents either true (1) or false (0). It is mainly used in conditional statements.​
Example:

$status = true;
echo $status; // Output: 1 (true)

5. Array

A collection of multiple values stored under a single variable. It can store a list of related items.​
Example:

$fruits = array("Apple", "Banana", "Cherry");


echo $fruits[0]; // Output: Apple

6. Object

An instance of a class that stores properties and methods. It is used in object-oriented


programming.​
Example:

class Car {
public $brand = "Toyota";
}
$obj = new Car();
echo $obj->brand;

7. NULL

Represents an empty or uninitialized variable. It is used when a variable has no value.​


Example:

$var = NULL;

8. Resource

Holds a reference to external resources like database connections or file handles.​


Example:

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


3)Explain types of Operator with example.
7. Conditional operators
4)Write a PHP program to display arithmetic operation.

Code:

<?php
// Declare two numbers
$num1 = 20;
$num2 = 10;

// Perform arithmetic operations


$addition = $num1 + $num2;
$subtraction = $num1 - $num2;
$multiplication = $num1 * $num2;
$division = $num1 / $num2;
$modulus = $num1 % $num2;

// Display the results


echo "Addition of $num1 and $num2 is: $addition<br>";
echo "Subtraction of $num1 and $num2 is: $subtraction<br>";
echo "Multiplication of $num1 and $num2 is: $multiplication<br>";
echo "Division of $num1 and $num2 is: $division<br>";
echo "Modulus of $num1 and $num2 is: $modulus<br>";
?>

O/P

Addition of 20 and 10 is: 30


Subtraction of 20 and 10 is: 10
Multiplication of 20 and 10 is: 200
Division of 20 and 10 is: 2
Modulus of 20 and 10 is: 0

5)What is Class and Object? Explain with example.

Class and Object in PHP

Class:
A class is a user-defined data type that acts as a blueprint or template for creating objects. It
defines the properties (attributes) and methods (functions) that an object will have. Classes help
in organizing code, promoting reusability, and implementing object-oriented programming
concepts such as encapsulation, inheritance, and polymorphism.

Object:

An object is an instance of a class. When a class is defined, you can create multiple objects
based on it, each having its own set of properties and behaviors defined in the class. Objects
represent real-world entities, and they allow you to interact with the data and methods defined in
the class.

Example:
<?php
class Car {
public $brand;
public $color;

public function __construct($brand, $color) {


$this->brand = $brand;
$this->color = $color;
}

public function displayDetails() {


echo "This car is a $this->color $this->brand.";
}
}

$car1 = new Car("Toyota", "Red");


$car1->displayDetails(); // Output: This car is a Red Toyota.
?>

6)What is String? What are different types of string functions available in PHP?(CO2/U)

A string in PHP is a sequence of characters used to store and manipulate text. Strings are one of
the most commonly used data types and can include letters, numbers, and special characters.

You can create strings in PHP using:

●​ Single quotes (' ')


●​ Double quotes (" ")

7)Explain following string functions with example.


i)str_replace() ii)ucwords() iii)strlen() iv)str_word_count()

1.​ str_replace()​

○​ Description: The str_replace() function is used to search for specific words


or substrings in a string and replace them with new words or substrings. It is
particularly useful when you want to modify the content of a string dynamically.
This function is case-sensitive, meaning it will only replace exact matches.

Example:​
echo str_replace("World", "PHP", "Hello World");
Output:​
Hello PHP

2.​ ucwords()​

○​ Description: The ucwords() function capitalizes the first character of each


word in a string. Words are determined by spaces, and this function is commonly
used to format strings into title case, such as names or headings. It does not
modify other characters in the string.

Example:​
echo ucwords("hello world");

○​
○​ Output:​
Hello World
3.​ strlen()​

○​ Description: The strlen() function returns the number of characters in a


string, including spaces and special characters. It is widely used for validation,
such as checking if a string meets certain length requirements.

Example:​
echo strlen("Hello");

○​
○​ Output:​
5
4.​ str_word_count()​

○​ Description: The str_word_count() function counts the number of words in


a string. It considers words as sequences of characters separated by spaces, tabs,
or other word delimiters. This function is useful when analyzing text or validating
word count limits.

Example:​
echo str_word_count("Hello World");

○​
○​ Output:​
2

8)What is Inheritance? Explain with example.(CO3/U)

What is Inheritance?

Inheritance is a concept in Object-Oriented Programming (OOP) where a class (child/derived


class) inherits properties and methods from another class (parent/base class). It helps in code
reusability, extensibility, and creating a hierarchical relationship between classes.

Key Benefits of Inheritance

1.​ Promotes code reusability.


2.​ Establishes a hierarchical relationship between classes.
3.​ Facilitates extensibility for adding new features.

Types of Inheritance in PHP

1.​ Single Inheritance – A child class inherits from one parent class.
2.​ Multilevel Inheritance – A child class inherits from a parent class, which itself is a child
of another class.
3.​ Hierarchical Inheritance – Multiple child classes inherit from the same parent class.
4.​ Multiple Inheritance (via Interfaces) – PHP does not support direct multiple
inheritance but allows it using interfaces.

Example of Inheritance in PHP


<?php
// Parent class
class Animal {
public $name;

public function sound() {


echo "This animal makes a sound.";
}
}
// Child class
class Dog extends Animal {
public function sound() {
echo $this->name . " barks.";
}
}

// Create object of child class


$dog = new Dog();
$dog->name = "Buddy";
$dog->sound(); // Output: Buddy barks.
?>

(Not answering the repeated questions)

Test1(ch:1) 4 marks each

1)Explain variable scope in PHP.


2)List out the advantages and Disadvantages of PHP.

Advantages of PHP

1.​ Open Source: PHP is free to use and has a large supportive community.
2.​ Platform Independent: It runs on various platforms like Windows, Linux, macOS, etc.
3.​ Easy to Learn: PHP has a simple syntax, making it beginner-friendly.
4.​ Rich Library Support: Built-in libraries simplify tasks like file handling, database
interaction, and more.
5.​ Server-Side Efficiency: PHP is fast for server-side scripting and integrates well with
databases like MySQL.
6.​ CMS Compatibility: PHP powers popular CMS platforms like WordPress, Joomla, and
Drupal.
7.​ Scalable: Suitable for building applications of any size, from small websites to
large-scale applications.
8.​ Wide Framework Availability: Frameworks like Laravel and CodeIgniter accelerate
development.

Disadvantages of PHP
1.​ Security Issues: Open-source nature may lead to vulnerabilities if not coded securely.
2.​ Inconsistent Behavior: Older versions have inconsistencies and lack strict typing,
leading to potential bugs.
3.​ Not Suitable for Large Applications: Managing very large applications can be complex
due to PHP's loose structure.
4.​ Slow Execution: Interpreted nature can make PHP slower compared to compiled
languages like C++.
5.​ Limited Multithreading: PHP does not natively support multithreading, limiting
concurrency handling.
6.​ Over-Reliance on Community: As an open-source language, it heavily depends on
community support for updates and bug fixes.
7.​ Framework Dependency: For complex projects, developers often rely on external
frameworks, increasing dependency.

3)Describe loops in PHP.


4)Describe Data types in PHP in detail.
5)Explain types of Operator with example.

Test1(ch:2) 4 marks each

1)What is String? What are different types of string functions available in PHP?
2)How to create Function?Explain different types of function with example.

How to Create a Function in PHP?

A function in PHP is defined using the function keyword, followed by the function name and
a block of code.

Syntax:

function functionName() {
// Code to be executed
}

Types of Functions in PHP


1.​ User-Defined Functions – Custom functions created by the user.​

function greet() { echo "Hello!"; }
greet(); // Output: Hello!

1.​ Built-In Functions – Predefined functions in PHP.​



echo strlen("PHP"); // Output: 3
2.​ Parameterised Functions – Functions that take arguments.​

function add($a, $b) { return $a + $b; }

echo add(5, 3); // Output: 8

3.​ Default Parameter Functions – Functions with default values.​



function greetUser($name = "Guest") { echo "Hello, $name!"; }

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

4.​ Return Type Functions – Functions that return a value.​



function multiply($a, $b) { return $a * $b; }

echo multiply(4, 5); // Output: 20

5.​ Recursive Functions – Functions that call themselves.​



function factorial($n) { return ($n <= 1) ? 1 : $n * factorial($n - 1); }

echo factorial(5); // Output: 120

3)Enlist types of arrays.Explain with example.

Types of Arrays in PHP

PHP supports three types of arrays:

1.​ Indexed Array – Stores values with numeric indexes.


2.​ Associative Array – Uses named keys instead of numeric indexes.
3.​ Multidimensional Array – Contains arrays within an array.

1. Indexed Array

Elements are stored with numeric indexes starting from 0.​


Example:

$cars = array("Volvo", "BMW", "Toyota");


echo $cars[0]; // Output: Volvo

2. Associative Array

Uses named keys instead of numeric indexes.​


Example:

$student = array("name" => "John", "age" => 20, "grade" => "A");
echo $student["name"]; // Output: John

3. Multidimensional Array

Contains multiple arrays inside an array.​


Example:

$students = array(
array("John", 20, "A"),
array("Emma", 22, "B")
);
echo $students[0][0]; // Output: John

4)Explain, i)Extract()
ii)Compact()
iii)Implode()
iv)Explode()
v)array_flip()
PHP Functions Explanation
extract() – Converts array keys into variable names and assigns their values. It helps in
dynamically creating variables from an array.​

$data = array("name" => "John", "age" => 25);
extract($data);
echo $name; // Output: John

1.​ compact() – Creates an array from existing variables. It is useful when collecting
multiple variables into an array.​

$name = "John"; $age = 25;

$result = compact("name", "age");


print_r($result);

2.​ implode() – Joins array elements into a single string using a specified separator. It is
useful for converting arrays to readable text.​

$arr = array("Hello", "World");

echo implode(" ", $arr); // Output: Hello World

3.​ explode() – Splits a string into an array based on a delimiter. It is often used for
processing CSV or space-separated data.​

$str = "Hello,World";

print_r(explode(",", $str));

4.​ array_flip() – Swaps keys with their respective values in an array. It is useful when
reversing key-value pairs.​

$arr = array("a" => "apple", "b" => "banana");

print_r(array_flip($arr));

You might also like