C. Missing initial value causes $carry to be null.
D. The echo statement is missing parentheses.
Solution
Step 1: Check initial value usage
No initial value is given, so $carry starts as null.
Step 2: Understand effect on empty array
With empty array and no initial, array_reduce returns null without calling the callback.
Final Answer:
Missing initial value causes $carry to be null. -> Option C
Quick Check:
Initial value needed for empty arrays [OK]
Hint: Always provide initial value to avoid null carry [OK]
Common Mistakes:
Assuming callback parameters are reversed
Thinking array_reduce fails on empty arrays without initial
Ignoring PHP syntax for echo
5. Given an array of strings ['apple', 'banana', 'cherry'], how can you use array_reduce to create a single string with all fruits separated by commas (e.g., 'apple,banana,cherry')?
hard
A. Use array_reduce with callback concatenating carry and item with a comma, initial value as empty string.
B. Use array_reduce with callback adding carry and item as numbers, initial value 0.
C. Use array_reduce with callback returning only the last item, no initial value.
D. Use array_reduce with callback multiplying carry and item, initial value 1.
Solution
Step 1: Understand the goal
We want to join strings with commas into one string.
Step 2: Design the callback
Callback should add a comma between carry and item, starting with empty string.
Step 3: Avoid leading comma
Use a condition to avoid comma before first item or trim later.
Final Answer:
Use array_reduce with callback concatenating carry and item with a comma, initial value as empty string. -> Option A
Quick Check:
Concatenate strings with commas using array_reduce [OK]
Hint: Concatenate strings with commas, start with empty string [OK]
Common Mistakes:
Adding strings as numbers causing errors
Not providing initial value causing null carry
Using multiplication on strings
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.