Q
What will be the output of the following PHP code?
<?php
function sum($a, $b = 5) {
return $a + $b;
}
echo sum(3);
?

Answer & Solution

Answer: Option B
Solution:
The output of the code will be 8 because the sum() function accepts two arguments $a and $b, with $b having a default value of 5. When the function is called with only one argument (3), the default value of $b (5) is used, resulting in the sum of 3 and 5 being returned.
Related Questions on Average

Which PHP feature allows specifying default values for function arguments?

A). Default arguments

B). Optional parameters

C). Variable-length argument lists

D). All of the above

What is the output of the following PHP code?
<?php
function multiply(...$args) {
$result = 1;
foreach ($args as $value) {
$result *= $value;
}
return $result;
}
echo multiply(2, 3, 4);
?

A). 24

B). 9

C). 6

D). 2

What will be the output of the following PHP code?
<?php
$greet = function($name) {
return 'Hello, $name!';
};
echo $greet('John');
?

A). Hello, John!

B). Hello, $name!

C). function($name) { return 'Hello, $name!'; }

D). John

Which PHP feature allows defining functions with variable-length argument lists?

A). Dynamic functions

B). Variable arguments

C). Varargs

D). All of the above

Which PHP keyword is used to pass a function as an argument to another function?

A). Dynamic functions

B). Anonymous functions

C). Callbacks

D). All of the above

What will be the output of the following PHP code?
<?php
function add($a, $b) {
return $a + $b;
}
$result = add(5, 3);
echo $result;
?

A). 8

B). add(5, 3)

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

D). $a + $b

What will be the output of the following PHP code?
<?php
function greet() {
echo 'Hello, World!';
}
if (function_exists('greet')) {
greet();
} else {
echo 'Function does not exist';
}
?

A). Hello, World!

B). Function does not exist

C). Undefined function: greet

D). Function greet() { echo 'Hello, World!'; }

Which of the following statements about returning values from PHP functions is true?

A). PHP functions can return multiple values simultaneously

B). PHP functions cannot return values

C). PHP functions must always return a value

D). PHP functions can only return values of type string

Which keyword is used to define default parameter values in PHP functions?

A). default

B). var

C). const

D). None of the above

What will be the output of the following PHP code?
<?php
function factorial($n) {
$result = 1;
for ($i = 1; $i <= $n; $i++) {
$result *= $i;
}
return $result;
}
echo factorial(5);
?

A). 120

B). 5

C). Undefined function: factorial

D). Function factorial($n) { $result = 1; for ($i = 1; $i <= $n; $i++) { $result *= $i; } return $result; }