Ct-1 PHP
Ct-1 PHP
Question Bank :
(2marks)
1)List out the advantages of 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:
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) }
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.
$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:
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, ...);
Example:
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
Output:
I like Volvo, BMW and Toyota.
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);
Output:
Name: John, Age: 30, City: New York
Syntax:
compact(var1, var2, ...);
Example:
<?php
$firstname = "Peter";
$lastname = "Griffin";
$age = 41;
print_r($result);
?>
Output:
Array ( [firstname] => Peter [lastname] => Griffin [age] => 41 )
7)Explain array_flip() function with example.
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 )
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);
?>
Syntax:
foreach($array as $value) {
// Code to be executed
}
Example:
<?php
$colors = array("Red", "Green", "Blue");
foreach($colors as $color) {
echo "Color: $color <br>";
}
?>
● 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.
Syntax:
class Car {
public $brand;
function __construct($brand) {
$this->brand = $brand;
echo "Car object for $brand created!";
}
}
-------------------------------------------------------------------------------------------------------------------------------
(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"
);
Output:
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:
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:
6. Object
class Car {
public $brand = "Toyota";
}
$obj = new Car();
echo $obj->brand;
7. NULL
$var = NULL;
8. Resource
Code:
<?php
// Declare two numbers
$num1 = 20;
$num2 = 10;
O/P
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;
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.
1. str_replace()
Example:
echo str_replace("World", "PHP", "Hello World");
Output:
Hello PHP
2. ucwords()
Example:
echo ucwords("hello world");
○
○ Output:
Hello World
3. strlen()
Example:
echo strlen("Hello");
○
○ Output:
5
4. str_word_count()
Example:
echo str_word_count("Hello World");
○
○ Output:
2
What is Inheritance?
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.
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.
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.
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
}
1. Indexed Array
2. Associative Array
$student = array("name" => "John", "age" => 20, "grade" => "A");
echo $student["name"]; // Output: John
3. Multidimensional Array
$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;
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");
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));