B. Return statement split incorrectly, returns nothing
C. Variable $product is undefined
D. Function missing closing brace
Solution
Step 1: Analyze the return statement split
The return is on one line alone, so PHP treats it as returning nothing immediately.
Step 2: Understand effect of line break after return
The next line $product; is unreachable and not part of return, causing function to return null.
Final Answer:
Return statement split incorrectly, returns nothing -> Option B
Quick Check:
Return must be on same line as value [OK]
Hint: Keep return and value on same line to avoid empty return [OK]
Common Mistakes:
Splitting return and value on separate lines
Assuming return reads next line automatically
Ignoring PHP's automatic semicolon insertion
5. You want a PHP function that returns the first non-empty string from an array. Which function correctly returns the first non-empty string or null if none found?
hard
A. function firstNonEmpty(array $arr) {
foreach ($arr as $str) {
if ($str) {
return $str;
}
}
return '';
}
B. function firstNonEmpty(array $arr) {
foreach ($arr as $str) {
if (isset($str)) {
return $str;
}
}
return null;
}
C. function firstNonEmpty(array $arr) {
foreach ($arr as $str) {
if ($str !== '') {
return $str;
}
}
return null;
}
D. function firstNonEmpty(array $arr) {
foreach ($arr as $str) {
if ($str == '') {
return $str;
}
}
return null;
}
Solution
Step 1: Check condition for non-empty string
function firstNonEmpty(array $arr) {
foreach ($arr as $str) {
if ($str !== '') {
return $str;
}
}
return null;
} uses $str !== '' to find strings that are not empty exactly.
Step 2: Confirm return value if none found
function firstNonEmpty(array $arr) {
foreach ($arr as $str) {
if ($str !== '') {
return $str;
}
}
return null;
} returns null if no non-empty string is found, which is clear and intentional.
Final Answer:
function firstNonEmpty(array $arr) {
foreach ($arr as $str) {
if ($str !== '') {
return $str;
}
}
return null;
} -> Option C
Quick Check:
Return first non-empty string or null [OK]
Hint: Use strict check !== '' to find non-empty strings [OK]
Common Mistakes:
Using loose truthy check that skips '0' string
Returning empty string instead of null when none found
Returning on empty string instead of non-empty
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.