9. Which language construct can best represent the following series of if conditionals?
<?php
if($a == 'a') {
somefunction();
} else if ($a == 'b') {
anotherfunction();
} else if ($a == 'c') {
dosomething();
} else {
donothing();
}
?>
A. A switch statement without a default case
B. A recursive function call
C. A while statement
D. It is the only representation of this logic
E. A switch statement using a default case
Answer:
9. A series of if…else if code blocks checking for a single condition as above is a perfect place to use a switch statement:
<?php
switch($a) {
case 'a':
somefunction();
break;
case 'b':
anotherfunction();
break;
case 'c':
dosomething();
break;
default:
donothing();
}
?>
Because there is a catch-all else condition, a default case must also be provided for that situation. Answer E is correct.
10. What is the best way to iterate through the $myarray array, assuming you want to modify the value of each element as you do?
<?php
$myarray = array ("My String", "Another String", "Hi, Mom!");
?>
A. Using a for loop
B. Using a foreach loop
C. Using a while loop
D. Using a do…while loop
E. There is no way to accomplish this goal
Answer:
Normally, the foreach statement is the most appropriate construct for iterating through an array. However, because we are being asked to modify each element in the array, this option is not available, since foreach works on a copy of the array and would therefore result in added overhead. Although a while loop or a do…while loop might work, because the array is sequentially indexed a for statement is best suited for the task, making Answer A correct:
<?php
$myarray = array ("My String", "Another String", "Hi, Mom!");
for($i = 0; $i < count($myarray); $i++)
{
$myarray[$i] .= " ($i)";
}
?>