WEB TECHNOLOGIES - 1 : CHAPTER 2 : EXAM PREPARATION : TYBCS : SPPU PYQ

Q. Give function to check if a variable has value or not. 

Answer: 

isset($variable): The isset function checks if a variable is set and is not null. It returns true if the variable exists and has a value other than null, and false otherwise.


2. Write a PHP program to accept a string and print string divided into equal number of characters. (Consider spaces and enter character in calculation).


Q. What is function of bootstrap loader? 

Answer: Bootstrap loader loads operating system into the memory during computer startup. It transfers the control to main program.

Q. Write any two functions of decompose string with suitable example.

Answer: Functions to decompose a string:

1) Explode() function :

It breaks string into smaller parts and stores it into array:

Examples:

<?php

 $str = 'one|two|three';

$arr= explode('|',$str);

print_r($arr);

echo "<br>";

$arr= explode('|',$str,2);

print_r($arr);

echo "<br>";

$arr= explode('|',$str,-1);

print_r($arr);

echo "<br>";

>$arr= explode('|',$str);

print_r($arr);

echo "<br>";

?>

Output:

Array ( [0] => one [1] => two [2] => three[3] => four )

Array ( [0] => one [1] => two | three | four)

Array ( [0] => one [1] => two [2] => three )


2) strtok() function :

It splits a string into smaller strings (tokens). It gives new token each time.

Example: 

<?php

$inputString = "Hello, World,This ";

$d = ",";

// Tokenize the string using strtok

$token = strtok($inputString, $d);


// Loop through tokens and print each one

while ($token !== false) {

    echo "Token: $token\n";

    $token = strtok($d);

}

?>

Output: 

Token: Hello

Token: World

Token: This



1. What is an interpolation? 


Q. Differentiate between single quoted string and double quoted string. 

FeatureSingle-Quoted StringDouble-Quoted String
Variable substitutionNo variable substitutionVariables are interpolated
Escape sequencesLimited escape sequences (', \)Supports more escape sequences (\n, \t, etc.)
Literal interpretationLiteral interpretation of charactersSpecial characters have meanings (\n for newline, etc.)
PerformanceSlightly fasterSlightly slower
Use with special charactersIdeal for simple strings with fewer special charactersConvenient when dealing with variables and complex strings
Example$string = 'Hello, World!';$name = 'John'; $string = "Hello, $name!";

3. What is an introspection? 

 Introspection is the ability of a program to examine the type or properties of an object during runtime. It allows a program to analyze its own structure or the structure of other objects.


Explain any four introspective functions provided by PUP. 


4. What is regular expression? 

Answer: Definition: A regular expression (regex) is a sequence of characters that defines a search pattern for text processing.

Purpose: It is used for pattern matching within strings, enabling tasks like searching, validating, and manipulating text based on specified patterns.

Components: Regular expressions consist of literal characters, metacharacters, and special symbols, providing a concise and flexible way to represent patterns in text.


Example:

import re


# Example: Matching email addresses

text = "Contact us at support@example.com or info@company.com."

# Define the email pattern using a regular expression

email_pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'

# Using re.findall to find all email addresses in the text

matches = re.findall(email_pattern, text)

# Print the matches

print(matches)

Output:
['support@example.com', 'info@company.com']


Also write a PHP script using regular expression to check whether a small string appears at the end of a large string.


State True or False. 

The fun_num_args0 returns an array of all parameters provided to the function".

Answer: False

The func_get_args() function returns an array containing all the parameters passed to the function.


State True or false

"A function can have variable number of arguments." 

Answer: True

In many programming languages, including PHP, functions can be designed to accept a variable number of arguments.


How to find out the position of the first occurrence of a substring in a string? 

Answer: In PHP, you can use the strpos() function to find the position of the first occurrence of a substring in a string. 


<?php


// Example string

$s = "Hello, World! This is an example.";


// Substring to find

$word = "World";


// Find the position of the first occurrence

$pos = strpos($s, $word);


// Check if the substring was found

if ($pos !== false) {

    echo "The first occurrence of '$word' starts at position $pos";

} else {

    echo "Substring '$word' not found in the given string.";

}


?>


 Write a PHP script to accept three strings strl, str2, str3 from user. Search str2 in sal and replace all occurrences of str2 by str3. Also display total number of occurrences. 


Explain the concept of missing parameters to a function with suitable example. 


1. Explain the following functions with syntax and example:

(1) func_num_arg0 

(2) var_dump0 

(3)print_r0 

(4) soundex0 

(5) strxpos0.

Answer:

1) func_num_args()

Syntax: int func_num_args ( void )


Example: 

<?php

function exampleFunction() {

    $numArgs = func_num_args();

    echo "Number of arguments: $numArgs\n";

}


exampleFunction(1, 'two', 3.0);

?>


Output: 

Number of arguments: 3


2) var_dump()

Syntax: void var_dump ( mixed $expression [, mixed $... ] )


Example: 

<?php

$data = array('name' => 'John', 'age' => 30, 'city' => 'New York');

var_dump($data);

?>


Output : 

array(3) {

  ["name"]=>

  string(4) "John"

  ["age"]=>

  int(30)

  ["city"]=>

  string(8) "New York"

}


3) print_r()


Syntax: print_r(mixed $expression [, bool $return = false ] )


Example: <?php

$data = array('name' => 'John', 'age' => 30, 'city' => 'New York');

print_r($data);

?>


Output: 

Array

(

    [name] => John

    [age] => 30

    [city] => New York

)


4) Soundex()


The soundex() function in PHP is used to calculate the soundex key of a string. Soundex is a phonetic algorithm that represents words as a short code based on the way they sound, rather than their exact spelling. 

Syntax: string soundex ( string $str )


Example: <?php

$str1 = "hello";

$str2 = "holla";

echo soundex($str1) . "\n";

echo soundex($str2) . "\n";

?>

Output : 

H400

H400


5) strpos()

Syntax: mixed strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )


Example: 


<?php

$haystack = "Hello, World! This is an example.";

$needle = "World";

$position = strpos($haystack, $needle);

echo "Position of '$needle': $position\n";

?>


output: 

Position of 'World': 7



Explain variable function concept in PHP. 

In PHP, variable functions allow you to treat a variable as a function name and dynamically call that function. This enables flexibility in choosing which function to invoke based on conditions or user input


function greet($name) {

    echo "Hello, $name!";

}


$functionName = 'greet';

$functionName('John');


// Output: Hello, John!


Write a short note on: Introspection. 

Answer: 

In PHP, introspection involves the ability to examine and analyze the structure and characteristics of classes and objects during runtime.


How to find out the position of the first occurrence of a substring in a string? 


Explain the concept of missing parameters to a function with suitable example. 


Write an anonymous function to maximum of two numbers.


 Explain eregO function. List and explain (any three) with example special character used in regular function. 


1. What is the difference between echo() and print() functions? 

Answer: 

The echo() and print() functions in PHP are both used to output strings, but there are some key differences:


Return Value:

-echo() can take multiple parameters, does not return a value, and is used for outputting strings.

-print() always returns 1, so it can be used in expressions, but it is less commonly used for output.


Example : 

// Example with echo

echo "Hello", " ", "World"; // Valid with multiple parameters


// Example with print

$result = print "Hello World"; // Valid, but less common


Usage:

-echo() is more commonly used for outputting HTML or other content in PHP scripts.

-print() is less common due to its return value and is often used in situations where an expression is needed.


// Example with echo

echo "Welcome to PHP!";


// Example with print

$message = "Welcome to PHP!";

print $message;


Explain the following innctions with syntax and example: 

(1) func_get arg() 

(2) var_dumpO 

(3) strrev0 

(4) similar text()

(5) str_replace


2. Write the output of the following PHP script: 

<?php 

$str 'abc, pqr, len, xyz '; 

$a = explode( ' , ' , $str,3); 

print_r(fa); 

?> 


Ans:

Array

(

    [0] => abc

    [1] => pqr

    [2] => len, xyz

)



3. Consider a suing SAT = "PUNE UNIVERSITY"; write a PHP script to display above string in the format given below using built-in function: 

(1) pune university 

(2) PUNE UNIVERSITY 

(3) Pune university 

(4) Pune University 

(5) Pune University 

Answer:

<?php


$sat = "PUNE UNIVERSITY";


// (1) Convert to lowercase

$result1 = strtolower($sat);


// (2) Convert to uppercase

$result2 = strtoupper($sat);


// (3) Capitalize the first letter of each word

$result3 = ucwords(strtolower($sat));


// (4) Capitalize the first letter of the first word

$result4 = ucfirst(strtolower($sat));


// (5) Capitalize the first letter of each word

$result5 = ucwords($sat);


// Display the results

echo "(1) $result1\n";

echo "(2) $result2\n";

echo "(3) $result3\n";

echo "(4) $result4\n";

echo "(5) $result5\n";


?>



 What is an anonymous function? How Is it different from normal function? 

Answer: 

An anonymous function in PHP is a function without a specified name, often referred to as a "closure" or "lambda function."

It is defined using the function keyword without assigning a name, making it suitable for short-lived, small tasks.


Differences from Normal Functions:

-Anonymous functions lack a name, while normal functions have a name.

-Anonymous functions can be assigned to variables or passed as arguments directly.

-Anonymous functions can capture variables from the surrounding scope, creating closures, which is a feature not inherent in normal functions.


Example: 

$add = function ($a, $b) {

    return $a + $b;

};


$result = $add(3, 4);  // Result: 7



How to pass parameters to a function by reference? Explain with example. Also write its advantage. 


Write the purpose of explode function. 

Answer: 

-The explode() function in PHP is used to split a string into an array of substrings.

-It is particularly useful for breaking down strings with values separated by a common character, like CSV data or structured text.


Define an Introspection.


Write the output of the following script. 

<?php

 fa = 'PHP'; 

fb = interpolation'; 

echo $b; 

?> Ans. $a interpolation 


4. Explain the following functions with example: 

(i) ucwords() 

(0) trim() 

(iii) str-pad()

 (iv) udIrst() 

(v) chunk-split(). 


Explain different types of arguments passing to functions with example. 

Answer: In PHP, there are several ways to pass arguments to functions. Here are the main types:


1) Passing by Value:


-The default method in PHP.

-Copies the value of the argument into the function parameter.

-Changes to the parameter inside the function do not affect the original value.

Example:

function addTen($num) {

    $num += 10;

    return $num;

}


$value = 5;

$result = addTen($value);


echo $value;   // Output: 5

echo $result;  // Output: 15


2) Passing by reference: 

-Changes made to the parameter inside the function affect the original value.

-Declared using an ampersand (&) in both the function declaration and the function call.

function addTen(&$num) {

    $num += 10;

}

$value = 5;

addTen($value);

echo $value;   // Output: 15


3) Passing by Default Value (Default Argument):

- Allows you to specify default values for parameters.

- If no value is passed, the default value is used.


function greet($name = "Guest") {

    echo "Hello, $name!";

}

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

greet("John");   // Output: Hello, John!


4) Passing by Variable-length Argument List (Variadic Function):


- Allows a function to accept a variable number of arguments.

- Defined using three dots (...), often named ...$args.


function sum(...$numbers) {

    return array_sum($numbers);

}

echo sum(1, 2, 3, 4);   // Output: 10



Explain implode() with suitable example.

Answer: The implode() function in PHP is used to join array elements with a string. It takes an array as its first parameter and concatenates its elements into a string, separated by a specified delimiter.


Syntax: string implode ( string $glue , array $pieces )


Example: 


<?php


// Example array

$fruits = array('apple', 'banana', 'orange');


// Join array elements into a string separated by ', '

$result = implode(', ', $fruits);


echo $result;

// Output: apple, banana, orange


?>